Skip to content

Commit

Permalink
fix(eslint-plugin): [prefer-optional-chan] allow typeof for avoiding …
Browse files Browse the repository at this point in the history
…reference error
  • Loading branch information
yeonjuan committed Feb 14, 2024
1 parent 6a875b4 commit 68c8ac8
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
Expand Up @@ -3,6 +3,7 @@ import type {
TSESTree,
} from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import type { SourceCode } from '@typescript-eslint/utils/ts-eslint';
import {
isBigIntLiteralType,
isBooleanLiteralType,
Expand Down Expand Up @@ -122,6 +123,7 @@ function isValidFalseBooleanCheckType(
export function gatherLogicalOperands(
node: TSESTree.LogicalExpression,
parserServices: ParserServicesWithTypeInformation,
sourceCode: Readonly<SourceCode>,
options: PreferOptionalChainOptions,
): {
operands: Operand[];
Expand Down Expand Up @@ -157,7 +159,20 @@ export function gatherLogicalOperands(
comparedExpression.type === AST_NODE_TYPES.UnaryExpression &&
comparedExpression.operator === 'typeof'
) {
// typeof x === 'undefined'
const argument = comparedExpression.argument;
if (argument.type === AST_NODE_TYPES.Identifier) {
const reference = sourceCode
.getScope(argument)
.references.find(ref => ref.identifier.name === argument.name);

if (!reference?.resolved?.defs.length) {
// typeof window === 'undefined'
result.push({ type: OperandValidity.Invalid });
continue;
}
}

// typeof x.y === 'undefined'
result.push({
type: OperandValidity.Valid,
comparedName: comparedExpression.argument,
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/rules/prefer-optional-chain.ts
Expand Up @@ -179,6 +179,7 @@ export default createRule<
const { operands, newlySeenLogicals } = gatherLogicalOperands(
node,
parserServices,
context.sourceCode,
options,
);

Expand Down
Expand Up @@ -907,6 +907,7 @@ describe('hand-crafted cases', () => {
declare const x: 0n | { a: string };
!x || x.a;
`,
"typeof globalThis !== 'undefined' && globalThis.Array();",
],
invalid: [
// two errors
Expand Down Expand Up @@ -1915,6 +1916,42 @@ describe('hand-crafted cases', () => {
},
],
},
{
code: `
function foo(globalThis?: { Array: Function }) {
typeof globalThis !== 'undefined' && globalThis.Array();
}
`,
output: `
function foo(globalThis?: { Array: Function }) {
globalThis?.Array();
}
`,
errors: [
{
messageId: 'preferOptionalChain',
},
],
},
{
code: `
typeof globalThis !== 'undefined' && globalThis.Array && globalThis.Array();
`,
output: null,
errors: [
{
messageId: 'preferOptionalChain',
suggestions: [
{
messageId: 'optionalChainSuggest',
output: `
typeof globalThis !== 'undefined' && globalThis.Array?.();
`,
},
],
},
],
},
],
});
});
Expand Down

0 comments on commit 68c8ac8

Please sign in to comment.