Skip to content

Commit

Permalink
fix(eslint-plugin): [no-unnecessary-type-assertion] avoid remove cons…
Browse files Browse the repository at this point in the history
…t casting on template literals with expressions inside (typescript-eslint#8740)
  • Loading branch information
marcalexiei authored and yeonjuan committed Mar 31, 2024
1 parent 69204a4 commit 6d07f42
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
22 changes: 17 additions & 5 deletions packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts
Expand Up @@ -108,10 +108,23 @@ export default createRule<Options, MessageIds>({
);
}

function isConstVariableDeclaration(node: TSESTree.Node): boolean {
function isLiteralVariableDeclarationChangingTypeWithConst(
node: TSESTree.TSAsExpression | TSESTree.TSTypeAssertion,
): boolean {
/**
* If the type assertion is on a template literal WITH expressions we
* should keep the `const` casting
* @see https://github.com/typescript-eslint/typescript-eslint/issues/8737
*/
if (node.expression.type === AST_NODE_TYPES.TemplateLiteral) {
return node.expression.expressions.length === 0;
}

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const maybeDeclarationNode = node.parent.parent!;
return (
node.type === AST_NODE_TYPES.VariableDeclaration &&
node.kind === 'const'
maybeDeclarationNode.type === AST_NODE_TYPES.VariableDeclaration &&
maybeDeclarationNode.kind === 'const'
);
}

Expand Down Expand Up @@ -222,8 +235,7 @@ export default createRule<Options, MessageIds>({
const typeIsUnchanged = uncastType === castType;

const wouldSameTypeBeInferred = castType.isLiteral()
? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
isConstVariableDeclaration(node.parent.parent!)
? isLiteralVariableDeclarationChangingTypeWithConst(node)
: !isConstAssertion(node.typeAnnotation);

if (typeIsUnchanged && wouldSameTypeBeInferred) {
Expand Down
Expand Up @@ -277,9 +277,25 @@ function bar(items: string[]) {
`,
parserOptions: optionsWithOnUncheckedIndexedAccess,
},
// https://github.com/typescript-eslint/typescript-eslint/issues/8737
`
const myString = 'foo';
const templateLiteral = \`\${myString}-somethingElse\` as const;
`,
// https://github.com/typescript-eslint/typescript-eslint/issues/8737
`
const myString = 'foo';
const templateLiteral = <const>\`\${myString}-somethingElse\`;
`,
],

invalid: [
// https://github.com/typescript-eslint/typescript-eslint/issues/8737
{
code: 'const a = `a` as const;',
output: 'const a = `a`;',
errors: [{ messageId: 'unnecessaryAssertion', line: 1 }],
},
{
code: "const a = 'a' as const;",
output: "const a = 'a';",
Expand Down

0 comments on commit 6d07f42

Please sign in to comment.