Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,27 @@ export class Guard {
return this.containsToken('Identifier', 'arguments', node);
}

hasThisParameter(fn: AnyFunction): boolean {
if (fn.params.length === 0) {
return false;
}

const [firstParam] = fn.params;

if (firstParam.type === AST_NODE_TYPES.Identifier) {
return firstParam.name === 'this';
}

if (
firstParam.type === AST_NODE_TYPES.TSParameterProperty &&
firstParam.parameter.type === AST_NODE_TYPES.Identifier
) {
return firstParam.parameter.name === 'this';
}

return false;
}

containsTokenSequence(sequence: [string, string][], node: TSESTree.Node): boolean {
return this.sourceCode.getTokens(node).some((_, tokenIndex, tokens) => {
return sequence.every(([expectedType, expectedValue], i) => {
Expand Down Expand Up @@ -248,6 +269,7 @@ export class Guard {
!this.containsArguments(fn) &&
!this.containsNewDotTarget(fn);
if (!isSafe) return false;
if (this.hasThisParameter(fn)) return false;
if (this.isIgnored(fn)) return false;
if (this.options.allowNamedFunctions === true && this.isNamedFunction(fn)) return false;
if (this.options.allowNamedFunctions === 'only-expressions' && this.isNamedFunctionExpression(fn)) return false;
Expand Down
6 changes: 6 additions & 0 deletions test/rule.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,12 @@ describe('when function is already an arrow function, or cannot be converted to
{
code: 'function Foo() {if (!new.target) throw "Foo() must be called with new";}',
},
{
code: 'function withThis(this: HTMLElement, event: Event) { return event.type; }',
},
{
code: 'const withThis = function(this: void, value: number) { return value; };',
},
// assertion functions are unavailable in arrow functions
{
code: 'function foo(val: any): asserts val is string {}',
Expand Down