diff --git a/src/guard.ts b/src/guard.ts index c3010f3..a23f86b 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -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) => { @@ -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; diff --git a/test/rule.spec.ts b/test/rule.spec.ts index ab704c8..021db46 100644 --- a/test/rule.spec.ts +++ b/test/rule.spec.ts @@ -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 {}',