Skip to content

Commit

Permalink
feat(eslint-plugin): add quotes and box notation when required by rul…
Browse files Browse the repository at this point in the history
…e switch-exhaustiveness-check
  • Loading branch information
karishnu committed Jun 11, 2020
1 parent ee9f100 commit 28181a8
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions packages/eslint-plugin/src/rules/switch-exhaustiveness-check.ts
Expand Up @@ -42,7 +42,9 @@ export default createRule({
fixer: TSESLint.RuleFixer,
node: TSESTree.SwitchStatement,
missingBranchTypes: Array<ts.Type>,
symbolName?: string,
): TSESLint.RuleFix | null {
const identifierRegex = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/;
const lastCase =
node.cases.length > 0 ? node.cases[node.cases.length - 1] : null;
const caseIndent = lastCase
Expand All @@ -67,7 +69,17 @@ export default createRule({
continue;
}

const caseTest = checker.typeToString(missingBranchType);
const missingBranchName = missingBranchType.getSymbol()?.escapedName;
let caseTest = checker.typeToString(missingBranchType);

if (
symbolName &&
missingBranchName &&
!identifierRegex.test(missingBranchName.toString())
) {
caseTest = `${symbolName}['${missingBranchName}']`;
}

const errorMessage = `Not implemented yet: ${caseTest} case`;

missingCases.push(
Expand Down Expand Up @@ -101,6 +113,7 @@ export default createRule({

function checkSwitchExhaustive(node: TSESTree.SwitchStatement): void {
const discriminantType = getNodeType(node.discriminant);
const symbolName = discriminantType.getSymbol()?.escapedName;

if (discriminantType.isUnion()) {
const unionTypes = unionTypeParts(discriminantType);
Expand Down Expand Up @@ -139,7 +152,12 @@ export default createRule({
{
messageId: 'addMissingCases',
fix(fixer): TSESLint.RuleFix | null {
return fixSwitch(fixer, node, missingBranchTypes);
return fixSwitch(
fixer,
node,
missingBranchTypes,
symbolName?.toString(),
);
},
},
],
Expand Down

0 comments on commit 28181a8

Please sign in to comment.