Skip to content

fix(eslint-plugin): [no-useless-template-literals] rename to no-useless-template-expression (ALTERNATE VERSION, copy-pasted) #8919

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

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
---
description: 'Disallow unnecessary template expressions.'
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/no-useless-template-expression** for documentation.

This rule reports template literals that contain substitution expressions (also variously referred to as embedded expressions or string interpolations) that are unnecessary and can be simplified.

## Examples

<Tabs>
<TabItem value="❌ Incorrect">

```ts
// Static values can be incorporated into the surrounding template.

const ab1 = `${'a'}${'b'}`;
const ab2 = `a${'b'}`;

const stringWithNumber = `${'1 + 1 = '}${2}`;

const stringWithBoolean = `${'true is '}${true}`;

// Some simple expressions that are already strings
// can be rewritten without a template at all.

const text = 'a';
const wrappedText = `${text}`;

declare const intersectionWithString: string & { _brand: 'test-brand' };
const wrappedIntersection = `${intersectionWithString}`;
```

</TabItem>
<TabItem value="✅ Correct">

```ts
// Static values can be incorporated into the surrounding template.

const ab1 = `ab`;
const ab2 = `ab`;

const stringWithNumber = `1 + 1 = 2`;

const stringWithBoolean = `true is true`;

// Some simple expressions that are already strings
// can be rewritten without a template at all.

const text = 'a';
const wrappedText = text;

declare const intersectionWithString: string & { _brand: 'test-brand' };
const wrappedIntersection = intersectionWithString;
```

</TabItem>
</Tabs>

:::info
This rule does not aim to flag template literals without substitution expressions that could have been written as an ordinary string.
That is to say, this rule will not help you turn `` `this` `` into `"this"`.
If you are looking for such a rule, you can configure the [`quotes`](./quotes.mdx) rule to do this.
:::

## When Not To Use It

When you want to allow string expressions inside template literals.

## Related To

- [`restrict-template-expressions`](./restrict-template-expressions.mdx)
- [`quotes`](./quotes.mdx)
58 changes: 10 additions & 48 deletions packages/eslint-plugin/docs/rules/no-useless-template-literals.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
description: 'Disallow unnecessary template literals.'
description: 'Disallow unnecessary template expressions.'
---

import Tabs from '@theme/Tabs';
Expand All @@ -9,53 +9,15 @@ import TabItem from '@theme/TabItem';
>
> See **https://typescript-eslint.io/rules/no-useless-template-literals** for documentation.

This rule reports template literals that can be simplified to a normal string literal.
This rule reports template literals that contain substitution expressions (also variously referred to as embedded expressions or string interpolations) that are unnecessary and can be simplified.

## Examples
:::warning
This rule is being renamed to [`no-useless-template-expression`](./no-useless-template-expression.mdx).
After the creation of this rule, it was realized that the name `no-useless-template-literals` could be misleading, seeing as this rule only targets template literals with substitution expressions.
In particular, it does _not_ aim to flag useless template literals that look like `` `this` `` and could be simplified to `"this"`.
If you are looking for such a rule, you can configure the [`@stylistic/ts/quotes`](https://eslint.style/rules/ts/quotes) rule to do this.

<Tabs>
<TabItem value="❌ Incorrect">
The current name, `no-useless-template-literals`, will be removed in a future major version of typescript-eslint.
:::

```ts
const ab1 = `${'a'}${'b'}`;
const ab2 = `a${'b'}`;

const stringWithNumber = `${'1 + 1 = '}${2}`;

const stringWithBoolean = `${'true is '}${true}`;

const text = 'a';
const wrappedText = `${text}`;

declare const intersectionWithString: string & { _brand: 'test-brand' };
const wrappedIntersection = `${intersectionWithString}`;
```

</TabItem>
<TabItem value="✅ Correct">

```ts
const ab1 = 'ab';
const ab2 = 'ab';

const stringWithNumber = `1 + 1 = 2`;

const stringWithBoolean = `true is true`;

const text = 'a';
const wrappedText = text;

declare const intersectionWithString: string & { _brand: 'test-brand' };
const wrappedIntersection = intersectionWithString;
```

</TabItem>
</Tabs>

## When Not To Use It

When you want to allow string expressions inside template literals.

## Related To

- [`restrict-template-expressions`](./restrict-template-expressions.mdx)
{/* Intentionally Omitted: When Not To Use It */}
2 changes: 1 addition & 1 deletion packages/eslint-plugin/src/configs/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export = {
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/no-useless-empty-export': 'error',
'@typescript-eslint/no-useless-template-literals': 'error',
'@typescript-eslint/no-useless-template-expression': 'error',
'@typescript-eslint/no-var-requires': 'error',
'@typescript-eslint/non-nullable-type-assertion-style': 'error',
'no-throw-literal': 'off',
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/disable-type-checked.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export = {
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-return': 'off',
'@typescript-eslint/no-unsafe-unary-minus': 'off',
'@typescript-eslint/no-useless-template-expression': 'off',
'@typescript-eslint/no-useless-template-literals': 'off',
'@typescript-eslint/non-nullable-type-assertion-style': 'off',
'@typescript-eslint/only-throw-error': 'off',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export = {
'@typescript-eslint/no-unsafe-enum-comparison': 'error',
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-return': 'error',
'@typescript-eslint/no-useless-template-literals': 'error',
'@typescript-eslint/no-useless-template-expression': 'error',
'no-throw-literal': 'off',
'@typescript-eslint/only-throw-error': 'error',
'@typescript-eslint/prefer-includes': 'error',
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin/src/configs/strict-type-checked.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export = {
'@typescript-eslint/no-unused-vars': 'error',
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/no-useless-template-literals': 'error',
'@typescript-eslint/no-useless-template-expression': 'error',
'@typescript-eslint/no-var-requires': 'error',
'no-throw-literal': 'off',
'@typescript-eslint/only-throw-error': 'error',
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ import noUnusedVars from './no-unused-vars';
import noUseBeforeDefine from './no-use-before-define';
import noUselessConstructor from './no-useless-constructor';
import noUselessEmptyExport from './no-useless-empty-export';
import noUselessTemplateExpression from './no-useless-template-expression';
import noUselessTemplateLiterals from './no-useless-template-literals';
import noVarRequires from './no-var-requires';
import nonNullableTypeAssertionStyle from './non-nullable-type-assertion-style';
Expand Down Expand Up @@ -242,6 +243,7 @@ export default {
'no-use-before-define': noUseBeforeDefine,
'no-useless-constructor': noUselessConstructor,
'no-useless-empty-export': noUselessEmptyExport,
'no-useless-template-expression': noUselessTemplateExpression,
'no-useless-template-literals': noUselessTemplateLiterals,
'no-var-requires': noVarRequires,
'non-nullable-type-assertion-style': nonNullableTypeAssertionStyle,
Expand Down
175 changes: 175 additions & 0 deletions packages/eslint-plugin/src/rules/no-useless-template-expression.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import * as ts from 'typescript';

import {
createRule,
getConstrainedTypeAtLocation,
getParserServices,
getStaticStringValue,
isTypeFlagSet,
isUndefinedIdentifier,
} from '../util';

type MessageId = 'noUselessTemplateExpression';

export default createRule<[], MessageId>({
name: 'no-useless-template-expression',
meta: {
fixable: 'code',
type: 'suggestion',
docs: {
description: 'Disallow unnecessary template expressions',
recommended: 'strict',
requiresTypeChecking: true,
},
messages: {
noUselessTemplateExpression:
'Template literal expression is unnecessary and can be simplified.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const services = getParserServices(context);

function isUnderlyingTypeString(
expression: TSESTree.Expression,
): expression is TSESTree.StringLiteral | TSESTree.Identifier {
const type = getConstrainedTypeAtLocation(services, expression);

const isString = (t: ts.Type): boolean => {
return isTypeFlagSet(t, ts.TypeFlags.StringLike);
};

if (type.isUnion()) {
return type.types.every(isString);
}

if (type.isIntersection()) {
return type.types.some(isString);
}

return isString(type);
}

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

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

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) {
return;
}

const hasSingleStringVariable =
node.quasis.length === 2 &&
node.quasis[0].value.raw === '' &&
node.quasis[1].value.raw === '' &&
node.expressions.length === 1 &&
isUnderlyingTypeString(node.expressions[0]);

if (hasSingleStringVariable) {
context.report({
node: node.expressions[0],
messageId: 'noUselessTemplateExpression',
fix(fixer): TSESLint.RuleFix[] {
const [prevQuasi, nextQuasi] = node.quasis;

// Remove the quasis and backticks.
return [
fixer.removeRange([
prevQuasi.range[1] - 3,
node.expressions[0].range[0],
]),

fixer.removeRange([
node.expressions[0].range[1],
nextQuasi.range[0] + 2,
]),
];
},
});

return;
}

const fixableExpressions = node.expressions.filter(
expression =>
isLiteral(expression) ||
isTemplateLiteral(expression) ||
isUndefinedIdentifier(expression) ||
isInfinityIdentifier(expression) ||
isNaNIdentifier(expression),
);

fixableExpressions.forEach(expression => {
context.report({
node: expression,
messageId: 'noUselessTemplateExpression',
fix(fixer): TSESLint.RuleFix[] {
const index = node.expressions.indexOf(expression);
const prevQuasi = node.quasis[index];
const nextQuasi = node.quasis[index + 1];

// Remove the quasis' parts that are related to the current expression.
const fixes = [
fixer.removeRange([
prevQuasi.range[1] - 2,
expression.range[0],
]),

fixer.removeRange([
expression.range[1],
nextQuasi.range[0] + 1,
]),
];

const stringValue = getStaticStringValue(expression);

if (stringValue != null) {
const escapedValue = stringValue.replace(/([`$\\])/g, '\\$1');

fixes.push(fixer.replaceText(expression, escapedValue));
} else if (isTemplateLiteral(expression)) {
// Note that some template literals get handled in the previous branch too.
// Remove the beginning and trailing backtick characters.
fixes.push(
fixer.removeRange([
expression.range[0],
expression.range[0] + 1,
]),
fixer.removeRange([
expression.range[1] - 1,
expression.range[1],
]),
);
}

return fixes;
},
});
});
},
};
},
});
Loading
Loading