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): [no-unnecessary-condition] handle index signature type #5912

Merged
merged 1 commit into from Nov 15, 2022
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
7 changes: 6 additions & 1 deletion packages/eslint-plugin/src/rules/no-unnecessary-condition.ts
Expand Up @@ -554,7 +554,12 @@ export default createRule<Options, MessageId>({
type,
property.name,
);
return propType && isNullableType(propType, { allowUndefined: true });

if (propType) {
return isNullableType(propType, { allowUndefined: true });
}

return !!checker.getIndexInfoOfType(type, ts.IndexKind.String);
});
return (
!isOwnNullable && isNullableType(prevType, { allowUndefined: true })
Expand Down
Expand Up @@ -527,6 +527,24 @@ if (x) {
tsconfigRootDir: path.join(rootPath, 'unstrict'),
},
},
`
interface Foo {
[key: string]: [string] | undefined;
}

type OptionalFoo = Foo | undefined;
declare const foo: OptionalFoo;
foo?.test?.length;
`,
`
interface Foo {
[key: number]: [string] | undefined;
}

type OptionalFoo = Foo | undefined;
declare const foo: OptionalFoo;
foo?.[1]?.length;
`,
],
invalid: [
// Ensure that it's checking in all the right places
Expand Down Expand Up @@ -1548,5 +1566,36 @@ if (x) {
tsconfigRootDir: path.join(rootPath, 'unstrict'),
},
},
{
code: `
interface Foo {
test: string;
[key: string]: [string] | undefined;
}

type OptionalFoo = Foo | undefined;
declare const foo: OptionalFoo;
foo?.test?.length;
`,
output: `
interface Foo {
test: string;
[key: string]: [string] | undefined;
}

type OptionalFoo = Foo | undefined;
declare const foo: OptionalFoo;
foo?.test.length;
`,
errors: [
{
messageId: 'neverOptionalChain',
line: 9,
endLine: 9,
column: 10,
endColumn: 12,
},
],
},
],
});