From 62992b2fb7d1ba3a2f36cee372748760c187323c Mon Sep 17 00:00:00 2001 From: mdm317 Date: Thu, 2 Jan 2025 23:04:38 +0900 Subject: [PATCH] fix : work with enum --- .../rules/no-unnecessary-type-assertion.ts | 3 ++- .../no-unnecessary-type-assertion.test.ts | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) 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 c73d8717c3e1..d11a40f85825 100644 --- a/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts +++ b/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts @@ -226,7 +226,8 @@ export default createRule({ const wouldSameTypeBeInferred = castType.isLiteral() ? isImplicitlyNarrowedConstDeclaration(node) - : !isConstAssertion(node.typeAnnotation); + : checker.isTypeAssignableTo(castType, uncastType) && + !isConstAssertion(node.typeAnnotation); if (typeIsUnchanged && wouldSameTypeBeInferred) { context.report({ 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 db8309164efb..8853d0c111dd 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 @@ -1151,5 +1151,32 @@ const a = ''; const b: string | undefined = (a ? undefined : a); `, }, + { + code: ` +enum MyEnum { + Value1, +} + +declare const myEnum: MyEnum.Value1; + +const myEnumCast = myEnum as MyEnum.Value1; + `, + errors: [ + { + column: 20, + line: 8, + messageId: 'unnecessaryAssertion', + }, + ], + output: ` +enum MyEnum { + Value1, +} + +declare const myEnum: MyEnum.Value1; + +const myEnumCast = myEnum; + `, + }, ], });