From f76a1b3e63afda9f239e46f4ad5b36c1d7a6e8da Mon Sep 17 00:00:00 2001 From: Alexander T Date: Wed, 18 Mar 2020 21:06:57 +0200 Subject: [PATCH] feat(eslint-plugin): [no-unnec-type-assertion] allow const assertions (#1741) --- .../rules/no-unnecessary-type-assertion.md | 4 +++ .../rules/no-unnecessary-type-assertion.ts | 16 ++++++++-- .../no-unnecessary-type-assertion.test.ts | 32 +++++++++++++++++++ 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/packages/eslint-plugin/docs/rules/no-unnecessary-type-assertion.md b/packages/eslint-plugin/docs/rules/no-unnecessary-type-assertion.md index 14819c56bf7..4464b6483ef 100644 --- a/packages/eslint-plugin/docs/rules/no-unnecessary-type-assertion.md +++ b/packages/eslint-plugin/docs/rules/no-unnecessary-type-assertion.md @@ -43,6 +43,10 @@ const foo = 3; const foo = 3 as number; ``` +```ts +const foo = 'foo' as const; +``` + ```ts function foo(x: number | undefined): number { return x!; diff --git a/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts b/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts index dd4395b290b..4fe9f9a59d2 100644 --- a/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts +++ b/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts @@ -1,4 +1,7 @@ -import { TSESTree } from '@typescript-eslint/experimental-utils'; +import { + TSESTree, + AST_NODE_TYPES, +} from '@typescript-eslint/experimental-utils'; import { isObjectType, isObjectFlagSet, @@ -122,6 +125,14 @@ export default util.createRule({ return false; } + function isConstAssertion(node: TSESTree.TypeNode): boolean { + return ( + node.type === AST_NODE_TYPES.TSTypeReference && + node.typeName.type === AST_NODE_TYPES.Identifier && + node.typeName.name === 'const' + ); + } + return { TSNonNullExpression(node): void { const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node); @@ -201,7 +212,8 @@ export default util.createRule({ if ( options.typesToIgnore?.includes( sourceCode.getText(node.typeAnnotation), - ) + ) || + isConstAssertion(node.typeAnnotation) ) { return; } diff --git a/packages/eslint-plugin/tests/rules/no-unnecessary-type-assertion.test.ts b/packages/eslint-plugin/tests/rules/no-unnecessary-type-assertion.test.ts index e7248a9693e..4d1ae880e84 100644 --- a/packages/eslint-plugin/tests/rules/no-unnecessary-type-assertion.test.ts +++ b/packages/eslint-plugin/tests/rules/no-unnecessary-type-assertion.test.ts @@ -130,6 +130,38 @@ function Test(props: { `, filename: 'react.tsx', }, + { + code: ` +const a = [1, 2]; +const b = [3, 4]; +const c = [...a, ...b] as const; + `, + }, + { + code: `const a = [1, 2] as const;`, + }, + { + code: `const a = 'a' as const;`, + }, + { + code: `const a = { foo: 'foo' } as const`, + }, + { + code: ` +const a = [1, 2]; +const b = [3, 4]; +const c = [...a, ...b]; + `, + }, + { + code: `const a = [1, 2];`, + }, + { + code: `const a = 'a';`, + }, + { + code: `const a = { foo: 'foo' };`, + }, ], invalid: [