Skip to content

Commit

Permalink
fix(eslint-plugin): [no-useless-template-literals] report Infinity & …
Browse files Browse the repository at this point in the history
…NaN (typescript-eslint#8295)

* fix(eslint-plugin): [no-useless-template-literals] report Infinity & NaN

Closes typescript-eslint#8294

* remove unnecessary tests
  • Loading branch information
StyleShit authored and danvk committed Feb 4, 2024
1 parent 2ecc5e7 commit db2df24
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 4 deletions.
28 changes: 24 additions & 4 deletions packages/eslint-plugin/src/rules/no-useless-template-literals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,24 @@ export default createRule<[], MessageId>({
return isString(type);
}

function isLiteral(expression: TSESTree.Expression): boolean {
return expression.type === AST_NODE_TYPES.Literal;
}

function isInfinityIdentifier(expression: TSESTree.Expression): boolean {
return (
expression.type === AST_NODE_TYPES.Identifier &&
expression.name === 'Infinity'
);
}

function isNaNIdentifier(expression: TSESTree.Expression): boolean {
return (
expression.type === AST_NODE_TYPES.Identifier &&
expression.name === 'NaN'
);
}

return {
TemplateLiteral(node: TSESTree.TemplateLiteral): void {
if (node.parent.type === AST_NODE_TYPES.TaggedTemplateExpression) {
Expand Down Expand Up @@ -91,13 +109,15 @@ export default createRule<[], MessageId>({
return;
}

const literalsOrUndefinedExpressions = node.expressions.filter(
const fixableExpressions = node.expressions.filter(
(expression): expression is TSESTree.Literal | TSESTree.Identifier =>
expression.type === AST_NODE_TYPES.Literal ||
isUndefinedIdentifier(expression),
isLiteral(expression) ||
isUndefinedIdentifier(expression) ||
isInfinityIdentifier(expression) ||
isNaNIdentifier(expression),
);

literalsOrUndefinedExpressions.forEach(expression => {
fixableExpressions.forEach(expression => {
context.report({
node: expression,
messageId: 'noUselessTemplateLiteral',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,32 @@ ruleTester.run('no-useless-template-literals', rule, {
],
},

{
code: '`${Infinity}`;',
output: '`Infinity`;',
errors: [
{
messageId: 'noUselessTemplateLiteral',
line: 1,
column: 4,
endColumn: 12,
},
],
},

{
code: '`${NaN}`;',
output: '`NaN`;',
errors: [
{
messageId: 'noUselessTemplateLiteral',
line: 1,
column: 4,
endColumn: 7,
},
],
},

{
code: "`${'a'} ${'b'}`;",
output: '`a b`;',
Expand Down

0 comments on commit db2df24

Please sign in to comment.