Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy 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 fromall commits
Commits
Show all changes
17 commits
Select commitHold shift + click to select a range
6d0448b
feat: add option
developer-bandiSep 8, 2024
82f7a10
fix: test error
developer-bandiSep 8, 2024
5ac803c
fix: lint error
developer-bandiSep 9, 2024
fb1406a
fix: apply code reivew
developer-bandiOct 3, 2024
bef9823
fix: reflect code review
developer-bandiOct 10, 2024
c76867c
docs:
developer-bandiOct 15, 2024
e0c892e
docs: change option name
developer-bandiOct 15, 2024
55f761f
docs: considerDefaultExhaustiveForUnions option description edit
developer-bandiOct 16, 2024
d795c4f
docs: apply code reivew
developer-bandiOct 19, 2024
4b94e5c
Merge branch 'main' into feature/switch-exhaustiveness-check
developer-bandiOct 19, 2024
5b00672
fix: test and lint error
developer-bandiOct 19, 2024
d594720
fix:lint error
developer-bandiOct 19, 2024
718c6bb
fix heading issue
kirkwaiblingerOct 27, 2024
1203a7c
refactor to tabs
kirkwaiblingerOct 27, 2024
b03b724
Merge branch 'main' into feature/switch-exhaustiveness-check
kirkwaiblingerOct 27, 2024
3e1a24e
Update packages/eslint-plugin/docs/rules/switch-exhaustiveness-check.mdx
JoshuaKGoldbergOct 27, 2024
76c8716
fix text snapshots
JoshuaKGoldbergOct 27, 2024
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
View file
Open in desktop
Original file line numberDiff line numberDiff 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 DownExpand 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
View file
Open in desktop
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 abouthow customized files appear on GitHub.

Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp