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..d29bd1292d02 100644 --- a/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts +++ b/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts @@ -13,6 +13,7 @@ import { getDeclaration, getModifiers, getParserServices, + getTypeName, isNullableType, isTypeFlagSet, nullThrows, @@ -224,9 +225,13 @@ export default createRule({ const uncastType = services.getTypeAtLocation(node.expression); const typeIsUnchanged = isTypeUnchanged(uncastType, castType); - const wouldSameTypeBeInferred = castType.isLiteral() - ? isImplicitlyNarrowedConstDeclaration(node) - : !isConstAssertion(node.typeAnnotation); + const isAssertionTypeUnionStringlike = + castType.isUnion() && getTypeName(checker, castType) === 'string'; + + const wouldSameTypeBeInferred = + castType.isLiteral() || isAssertionTypeUnionStringlike + ? isImplicitlyNarrowedConstDeclaration(node) + : !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..a4d34d1881bb 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 @@ -358,6 +358,16 @@ if (Math.random()) { x!; `, }, + "let a = (Date.now() % 2 ? 'a' : 'b') as 'a' | 'b';", + ` + const state: 'expired' | 'pending' = 'pending'; + + function main() { + return { + type: \`\${state}Request\` as \`\${typeof state}Request\`, + }; + } + `, ], invalid: [ @@ -1151,5 +1161,16 @@ const a = ''; const b: string | undefined = (a ? undefined : a); `, }, + { + code: "const a = (Date.now() % 2 ? 'a' : 'b') as 'a' | 'b';", + errors: [ + { + column: 11, + line: 1, + messageId: 'unnecessaryAssertion', + }, + ], + output: `const a = (Date.now() % 2 ? 'a' : 'b');`, + }, ], });