Skip to content

feat(eslint-plugin): [switch-exhaustiveness-check] add considerDefaultExhaustiveForUnions option #9954

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 @@ -23,7 +23,7 @@ This rule reports when a `switch` statement over a value typed as a union of lit
If set to false, this rule will also report when a `switch` statement has a case for everything in a union and _also_ contains a `default` case. Thus, by setting this option to false, the rule becomes stricter.

When a `switch` statement over a union type is exhaustive, a final `default` case would be a form of dead code.
Additionally, if a new value is added to the union type, a `default` would prevent the `switch-exhaustiveness-check` rule from reporting on the new case not being handled in the `switch` statement.
Additionally, if a new value is added to the union type and you're using [`considerDefaultExhaustiveForUnions`](#considerDefaultExhaustiveForUnions), a `default` would prevent the `switch-exhaustiveness-check` rule from reporting on the new case not being handled in the `switch` statement.

#### `allowDefaultCaseForExhaustiveSwitch` Caveats

Expand Down Expand Up @@ -57,6 +57,57 @@ switch (value) {

Since `value` is a non-union type it requires the switch case to have a default clause only with `requireDefaultForNonUnion` enabled.

### `considerDefaultExhaustiveForUnions`

{/* insert option description */}

If set to true, a `switch` statement over a union type that includes a `default` case is considered exhaustive.
Otherwise, the rule enforces explicitly handling every constituent of the union type with their own explicit `case`.
Keeping this option disabled can be useful if you want to make sure every value added to the union receives explicit handling, with the `default` case reserved for reporting an error.

Examples of code with `{ considerDefaultExhaustiveForUnions: true }`:

<Tabs>
<TabItem value="❌ Incorrect">

```ts option='{ "considerDefaultExhaustiveForUnions": true }' showPlaygroundButton
declare const literal: 'a' | 'b';

switch (literal) {
case 'a':
break;
default:
break;
}
```

</TabItem>

<TabItem value="✅ Correct">

```ts option='{ "considerDefaultExhaustiveForUnions": true }' showPlaygroundButton
declare const literal: 'a' | 'b';

switch (literal) {
case 'a':
break;
case 'b':
break;
default:
break;
}

switch (literal) {
case 'a':
break;
case 'b':
break;
}
```

</TabItem>
</Tabs>

## Examples

When the switch doesn't have exhaustive cases, either filling them all out or adding a default will correct the rule's complaint.
Expand Down
40 changes: 35 additions & 5 deletions packages/eslint-plugin/src/rules/switch-exhaustiveness-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ type Options = [
* @default false
*/
requireDefaultForNonUnion?: boolean;

/**
* If `true`, the `default` clause is used to determine whether the switch statement is exhaustive for union types.
*
* @default false
*/
considerDefaultExhaustiveForUnions?: boolean;
},
];

Expand Down Expand Up @@ -70,6 +77,10 @@ export default createRule<Options, MessageIds>({
type: 'boolean',
description: `If 'true', allow 'default' cases on switch statements with exhaustive cases.`,
},
considerDefaultExhaustiveForUnions: {
type: 'boolean',
description: `If 'true', the 'default' clause is used to determine whether the switch statement is exhaustive for union type`,
},
requireDefaultForNonUnion: {
type: 'boolean',
description: `If 'true', require a 'default' clause for switches on non-union types.`,
Expand All @@ -81,12 +92,19 @@ export default createRule<Options, MessageIds>({
defaultOptions: [
{
allowDefaultCaseForExhaustiveSwitch: true,
considerDefaultExhaustiveForUnions: false,
requireDefaultForNonUnion: false,
},
],
create(
context,
[{ allowDefaultCaseForExhaustiveSwitch, requireDefaultForNonUnion }],
[
{
allowDefaultCaseForExhaustiveSwitch,
considerDefaultExhaustiveForUnions,
requireDefaultForNonUnion,
},
],
) {
const services = getParserServices(context);
const checker = services.program.getTypeChecker();
Expand Down Expand Up @@ -156,10 +174,13 @@ export default createRule<Options, MessageIds>({
const { defaultCase, missingLiteralBranchTypes, symbolName } =
switchMetadata;

// We only trigger the rule if a `default` case does not exist, since that
// would disqualify the switch statement from having cases that exactly
// match the members of a union.
if (missingLiteralBranchTypes.length > 0 && defaultCase === undefined) {
// Unless considerDefaultExhaustiveForUnions is enabled, the presence of a default case
// always makes the switch exhaustive.
if (!considerDefaultExhaustiveForUnions && defaultCase != null) {
return;
}

if (missingLiteralBranchTypes.length > 0) {
context.report({
node: node.discriminant,
messageId: 'switchIsNotExhaustive',
Expand Down Expand Up @@ -197,6 +218,8 @@ export default createRule<Options, MessageIds>({
): TSESLint.RuleFix {
const lastCase =
node.cases.length > 0 ? node.cases[node.cases.length - 1] : null;
const defaultCase = node.cases.find(caseEl => caseEl.test == null);

const caseIndent = lastCase
? ' '.repeat(lastCase.loc.start.column)
: // If there are no cases, use indentation of the switch statement and
Expand Down Expand Up @@ -244,6 +267,13 @@ export default createRule<Options, MessageIds>({
.join('\n');

if (lastCase) {
if (defaultCase) {
const beforeFixString = missingCases
.map(code => `${code}\n${caseIndent}`)
.join('');

return fixer.insertTextBefore(defaultCase, beforeFixString);
}
return fixer.insertTextAfter(lastCase, `\n${fixString}`);
}

Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading