Skip to content

Commit 9c5b857

Browse files
authored
fix(eslint-plugin): [unbound-method] handling of logical expr (#1440)
1 parent e329397 commit 9c5b857

File tree

2 files changed

+151
-238
lines changed

2 files changed

+151
-238
lines changed

Diff for: packages/eslint-plugin/src/rules/unbound-method.ts

+14-7
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ interface Config {
1414
ignoreStatic: boolean;
1515
}
1616

17-
type Options = [Config];
17+
export type Options = [Config];
1818

19-
type MessageIds = 'unbound';
19+
export type MessageIds = 'unbound';
2020

2121
export default util.createRule<Options, MessageIds>({
2222
name: 'unbound-method',
@@ -99,9 +99,9 @@ function isDangerousMethod(symbol: ts.Symbol, ignoreStatic: boolean): boolean {
9999
}
100100

101101
function isSafeUse(node: TSESTree.Node): boolean {
102-
const parent = node.parent!;
102+
const parent = node.parent;
103103

104-
switch (parent.type) {
104+
switch (parent?.type) {
105105
case AST_NODE_TYPES.IfStatement:
106106
case AST_NODE_TYPES.ForStatement:
107107
case AST_NODE_TYPES.MemberExpression:
@@ -118,9 +118,6 @@ function isSafeUse(node: TSESTree.Node): boolean {
118118
case AST_NODE_TYPES.ConditionalExpression:
119119
return parent.test === node;
120120

121-
case AST_NODE_TYPES.LogicalExpression:
122-
return parent.operator !== '||';
123-
124121
case AST_NODE_TYPES.TaggedTemplateExpression:
125122
return parent.tag === node;
126123

@@ -134,6 +131,16 @@ function isSafeUse(node: TSESTree.Node): boolean {
134131
case AST_NODE_TYPES.TSAsExpression:
135132
case AST_NODE_TYPES.TSTypeAssertion:
136133
return isSafeUse(parent);
134+
135+
case AST_NODE_TYPES.LogicalExpression:
136+
if (parent.operator === '&&' && parent.left === node) {
137+
// this is safe, as && will return the left if and only if it's falsy
138+
return true;
139+
}
140+
141+
// in all other cases, it's likely the logical expression will return the method ref
142+
// so make sure the parent is a safe usage
143+
return isSafeUse(parent);
137144
}
138145

139146
return false;

0 commit comments

Comments
 (0)