Skip to content

fix(eslint-plugin): [switch-exhaustiveness-check] add support for covering a missing property with undefined #10232

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

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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,15 @@ export default createRule<Options, MessageIds>({
continue;
}

// "missing", "optional" and "undefined" types are different runtime objects,
// but all of them have TypeFlags.Undefined type flag
if (
[...caseTypes].some(tsutils.isIntrinsicUndefinedType) &&
tsutils.isIntrinsicUndefinedType(intersectionPart)
) {
continue;
}

missingLiteralBranchTypes.push(intersectionPart);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -912,6 +912,48 @@ switch (value) {
},
],
},
{
code: `
function foo(x: string[]) {
switch (x[0]) {
case 'hi':
break;
case undefined:
break;
}
}
`,
languageOptions: {
parserOptions: {
project: './tsconfig.noUncheckedIndexedAccess.json',
projectService: false,
tsconfigRootDir: rootPath,
},
},
},
{
code: `
function foo(x: string[], y: string | undefined) {
const a = x[0];
if (typeof a === 'string') {
return;
}
switch (y) {
case 'hi':
break;
case a:
break;
}
}
`,
languageOptions: {
parserOptions: {
project: './tsconfig.noUncheckedIndexedAccess.json',
projectService: false,
tsconfigRootDir: rootPath,
},
},
},
],
invalid: [
{
Expand Down Expand Up @@ -2717,5 +2759,43 @@ switch (value) {
},
],
},
{
code: `
function foo(x: string[]) {
switch (x[0]) {
case 'hi':
break;
}
}
`,
errors: [
{
column: 11,
line: 3,
messageId: 'switchIsNotExhaustive',
suggestions: [
{
messageId: 'addMissingCases',
output: `
function foo(x: string[]) {
switch (x[0]) {
case 'hi':
break;
case undefined: { throw new Error('Not implemented yet: undefined case') }
}
}
`,
},
],
},
],
languageOptions: {
parserOptions: {
project: './tsconfig.noUncheckedIndexedAccess.json',
projectService: false,
tsconfigRootDir: rootPath,
},
},
},
],
});
Loading