Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [unbound-method] handling of logical expr #1440

Merged
merged 2 commits into from Jan 16, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 14 additions & 7 deletions packages/eslint-plugin/src/rules/unbound-method.ts
Expand Up @@ -14,9 +14,9 @@ interface Config {
ignoreStatic: boolean;
}

type Options = [Config];
export type Options = [Config];

type MessageIds = 'unbound';
export type MessageIds = 'unbound';

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

function isSafeUse(node: TSESTree.Node): boolean {
const parent = node.parent!;
const parent = node.parent;

switch (parent.type) {
switch (parent?.type) {
case AST_NODE_TYPES.IfStatement:
case AST_NODE_TYPES.ForStatement:
case AST_NODE_TYPES.MemberExpression:
Expand All @@ -118,9 +118,6 @@ function isSafeUse(node: TSESTree.Node): boolean {
case AST_NODE_TYPES.ConditionalExpression:
return parent.test === node;

case AST_NODE_TYPES.LogicalExpression:
return parent.operator !== '||';

case AST_NODE_TYPES.TaggedTemplateExpression:
return parent.tag === node;

Expand All @@ -134,6 +131,16 @@ function isSafeUse(node: TSESTree.Node): boolean {
case AST_NODE_TYPES.TSAsExpression:
case AST_NODE_TYPES.TSTypeAssertion:
return isSafeUse(parent);

case AST_NODE_TYPES.LogicalExpression:
if (parent.operator === '&&' && parent.left === node) {
// this is safe, as && will return the left if and only if it's falsy
return true;
}

// in all other cases, it's likely the logical expression will return the method ref
// so make sure the parent is a safe usage
return isSafeUse(parent);
}

return false;
Expand Down