From 53dc34d3917b90c8ab0324fe8054619ddee98003 Mon Sep 17 00:00:00 2001 From: YeonJuan Date: Thu, 17 Dec 2020 07:07:52 +0900 Subject: [PATCH] fix(eslint-plugin): [non-nullable-type-assertion-style] handle const assertion (#2881) --- .../non-nullable-type-assertion-style.ts | 19 ++++++++++++++++++- .../non-nullable-type-assertion-style.test.ts | 3 +++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/packages/eslint-plugin/src/rules/non-nullable-type-assertion-style.ts b/packages/eslint-plugin/src/rules/non-nullable-type-assertion-style.ts index 9bb099ef88c..eef8c58445f 100644 --- a/packages/eslint-plugin/src/rules/non-nullable-type-assertion-style.ts +++ b/packages/eslint-plugin/src/rules/non-nullable-type-assertion-style.ts @@ -1,4 +1,7 @@ -import { TSESTree } from '@typescript-eslint/experimental-utils'; +import { + AST_NODE_TYPES, + TSESTree, +} from '@typescript-eslint/experimental-utils'; import * as tsutils from 'tsutils'; import * as ts from 'typescript'; @@ -69,10 +72,24 @@ export default util.createRule({ return true; }; + const isConstAssertion = ( + node: TSESTree.TSTypeAssertion | TSESTree.TSAsExpression, + ): boolean => { + return ( + node.typeAnnotation.type === AST_NODE_TYPES.TSTypeReference && + node.typeAnnotation.typeName.type === AST_NODE_TYPES.Identifier && + node.typeAnnotation.typeName.name === 'const' + ); + }; + return { 'TSAsExpression, TSTypeAssertion'( node: TSESTree.TSTypeAssertion | TSESTree.TSAsExpression, ): void { + if (isConstAssertion(node)) { + return; + } + const originalTypes = getTypesIfNotLoose(node.expression); if (!originalTypes) { return; diff --git a/packages/eslint-plugin/tests/rules/non-nullable-type-assertion-style.test.ts b/packages/eslint-plugin/tests/rules/non-nullable-type-assertion-style.test.ts index 45ca1774d30..33c603135f5 100644 --- a/packages/eslint-plugin/tests/rules/non-nullable-type-assertion-style.test.ts +++ b/packages/eslint-plugin/tests/rules/non-nullable-type-assertion-style.test.ts @@ -51,6 +51,9 @@ declare const x: T | number; const y = x as NonNullable; `, + ` +const foo = [] as const; + `, ], invalid: [