Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [no-unnecessary-type-assertion] avoid remove const casting on template literals with expressions inside #8740

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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