8000 fix(eslint-plugin): [unbound-method] ignore assignments _to_ methods … · ryanwang520/typescript-eslint@6b4680b · GitHub
[go: up one dir, main page]

Skip to content

Commit 6b4680b

Browse files
authored
fix(eslint-plugin): [unbound-method] ignore assignments _to_ methods (typescript-eslint#1736)
1 parent d44c0f9 commit 6b4680b

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

packages/eslint-plugin/src/rules/unbound-method.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,9 @@ function isSafeUse(node: TSESTree.Node): boolean {
241241
case AST_NODE_TYPES.BinaryExpression:
242242
return ['instanceof', '==', '!=', '===', '!=='].includes(parent.operator);
243243

244+
case AST_NODE_TYPES.AssignmentExpression:
245+
return parent.operator === '=' && node === parent.left;
246+
244247
case AST_NODE_TYPES.TSNonNullExpression:
245248
case AST_NODE_TYPES.TSAsExpression:
246249
case AST_NODE_TYPES.TSTypeAssertion:

packages/eslint-plugin/tests/rules/unbound-method.test.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,9 @@ ruleTester.run('unbound-method', rule, {
147147

148148
"typeof ContainsMethods.boundStatic === 'function';",
149149
"typeof ContainsMethods.unboundStatic === 'function';",
150+
151+
'instance.unbound = () => {};',
152+
'instance.unbound = instance.unbound.bind(instance);',
150153
].map(addContainsMethodsClass),
151154
`
152155
interface RecordA {
@@ -211,6 +214,15 @@ const x: OptionalMethod = {};
211214
declare const myCondition: boolean;
212215
if (myCondition || x.mightBeDefined) {
213216
console.log('hello world');
217+
}
218+
`,
219+
// https://github.com/typescript-eslint/typescript-eslint/issues/1256
220+
`
221+
class A {
222+
unbound(): void {
223+
this.unbound = undefined;
224+
this.unbound = this.unbound.bind(this);
225+
}
214226
}
215227
`,
216228
],
@@ -336,5 +348,24 @@ const x = CommunicationError.prototype.foo;
336348
},
337349
],
338350
},
351+
{
352+
code: `
353+
class Foo {
354+
unbound() {}
355+
}
356+
const instance = new Foo();
357+
358+
let x;
359+
360+
x = instance.unbound; // THIS SHOULD ERROR
361+
instance.unbound = x; // THIS SHOULD NOT
362+
`,
363+
errors: [
364+
{
365+
line: 9,
366+
messageId: 'unbound',
367+
},
368+
],
369+
},
339370
],
340371
});

0 commit comments

Comments
 (0)
0