Skip to content

Commit

Permalink
fix(eslint-plugin): [no-unnecessary-condition] handle union array and…
Browse files Browse the repository at this point in the history
… tuple type (#8592)
  • Loading branch information
yeonjuan committed Mar 6, 2024
1 parent ef0e5cc commit 25e6518
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
9 changes: 7 additions & 2 deletions packages/eslint-plugin/src/rules/no-unnecessary-condition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,16 @@ export default createRule<Options, MessageId>({

function nodeIsArrayType(node: TSESTree.Expression): boolean {
const nodeType = getConstrainedTypeAtLocation(services, node);
return checker.isArrayType(nodeType);
return tsutils
.unionTypeParts(nodeType)
.some(part => checker.isArrayType(part));
}

function nodeIsTupleType(node: TSESTree.Expression): boolean {
const nodeType = getConstrainedTypeAtLocation(services, node);
return checker.isTupleType(nodeType);
return tsutils
.unionTypeParts(nodeType)
.some(part => checker.isTupleType(part));
}

function isArrayIndexExpression(node: TSESTree.Expression): boolean {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,20 @@ if (arr?.[42]) {
}
`,
`
type ItemA = { bar: string; baz: string };
type ItemB = { bar: string; qux: string };
declare const foo: ItemA[] | ItemB[];
foo[0]?.bar;
`,
`
type TupleA = [string, number];
type TupleB = [string, number];
declare const foo: TupleA | TupleB;
declare const index: number;
foo[index]?.toString();
`,
`
declare const returnsArr: undefined | (() => string[]);
if (returnsArr?.()[42]) {
}
Expand Down

0 comments on commit 25e6518

Please sign in to comment.