Skip to content

Commit 704b0bc

Browse files
authored
fix: do not convert functions where first parameter is this (#64)
1 parent 1d038c8 commit 704b0bc

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/guard.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,27 @@ export class Guard {
154154
return this.containsToken('Identifier', 'arguments', node);
155155
}
156156

157+
hasThisParameter(fn: AnyFunction): boolean {
158+
if (fn.params.length === 0) {
159+
return false;
160+
}
161+
162+
const [firstParam] = fn.params;
163+
164+
if (firstParam.type === AST_NODE_TYPES.Identifier) {
165+
return firstParam.name === 'this';
166+
}
167+
168+
if (
169+
firstParam.type === AST_NODE_TYPES.TSParameterProperty &&
170+
firstParam.parameter.type === AST_NODE_TYPES.Identifier
171+
) {
172+
return firstParam.parameter.name === 'this';
173+
}
174+
175+
return false;
176+
}
177+
157178
containsTokenSequence(sequence: [string, string][], node: TSESTree.Node): boolean {
158179
return this.sourceCode.getTokens(node).some((_, tokenIndex, tokens) => {
159180
return sequence.every(([expectedType, expectedValue], i) => {
@@ -248,6 +269,7 @@ export class Guard {
248269
!this.containsArguments(fn) &&
249270
!this.containsNewDotTarget(fn);
250271
if (!isSafe) return false;
272+
if (this.hasThisParameter(fn)) return false;
251273
if (this.isIgnored(fn)) return false;
252274
if (this.options.allowNamedFunctions === true && this.isNamedFunction(fn)) return false;
253275
if (this.options.allowNamedFunctions === 'only-expressions' && this.isNamedFunctionExpression(fn)) return false;

test/rule.spec.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,12 @@ describe('when function is already an arrow function, or cannot be converted to
143143
{
144144
code: 'function Foo() {if (!new.target) throw "Foo() must be called with new";}',
145145
},
146+
{
147+
code: 'function withThis(this: HTMLElement, event: Event) { return event.type; }',
148+
},
149+
{
150+
code: 'const withThis = function(this: void, value: number) { return value; };',
151+
},
146152
// assertion functions are unavailable in arrow functions
147153
{
148154
code: 'function foo(val: any): asserts val is string {}',

0 commit comments

Comments
 (0)