Skip to content

fix(eslint-plugin): [no-unnecessary-template-expression] report unnecessary template string in type context #9991

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
201 changes: 199 additions & 2 deletions packages/eslint-plugin/src/rules/no-unnecessary-template-expression.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import type {
AST_NODE_TYPES,
TSESLint,
TSESTree,
} from '@typescript-eslint/utils';
import * as ts from 'typescript';

import {
Expand Down Expand Up @@ -266,6 +269,200 @@ export default createRule<[], MessageId>({
});
}
},
TSTemplateLiteralType(node: TSESTree.TSTemplateLiteralType): void {
if (node.parent.type === AST_NODE_TYPES.TaggedTemplateExpression) {
return;
}

const isUnderlyingTypeString2 = (expression: TSESTree.TypeNode) => {
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);
};

// only wrapped by {} ex) type a = `${"test"}`
const hasSingleStringVariable =
node.quasis.length === 2 &&
node.quasis[0].value.raw === '' &&
node.quasis[1].value.raw === '' &&
node.types.length === 1 &&
isUnderlyingTypeString2(node.types[0]);

if (hasSingleStringVariable) {
context.report({
node: node.types[0],
messageId: 'noUnnecessaryTemplateExpression',
fix(fixer): TSESLint.RuleFix | null {
const wrappingCode = getMovedNodeCode({
sourceCode: context.sourceCode,
nodeToMove: node.types[0],
destinationNode: node,
});

return fixer.replaceText(node, wrappingCode);
},
});

return;
}

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

// let nextCharacterIsOpeningCurlyBrace = false;

// for (const expression of fixableExpressions) {
// const fixers: ((fixer: TSESLint.RuleFixer) => TSESLint.RuleFix[])[] =
// [];
// const index = node.expressions.indexOf(expression);
// const prevQuasi = node.quasis[index];
// const nextQuasi = node.quasis[index + 1];

// if (nextQuasi.value.raw.length !== 0) {
// nextCharacterIsOpeningCurlyBrace =
// nextQuasi.value.raw.startsWith('{');
// }

// if (isLiteral(expression)) {
// let escapedValue = (
// typeof expression.value === 'string'
// ? // The value is already a string, so we're removing quotes:
// // "'va`lue'" -> "va`lue"
// expression.raw.slice(1, -1)
// : // The value may be one of number | bigint | boolean | RegExp | null.
// // In regular expressions, we escape every backslash
// String(expression.value).replaceAll('\\', '\\\\')
// )
// // The string or RegExp may contain ` or ${.
// // We want both of these to be escaped in the final template expression.
// //
// // A pair of backslashes means "escaped backslash", so backslashes
// // from this pair won't escape ` or ${. Therefore, to escape these
// // sequences in the resulting template expression, we need to escape
// // all sequences that are preceded by an even number of backslashes.
// //
// // This RegExp does the following transformations:
// // \` -> \`
// // \\` -> \\\`
// // \${ -> \${
// // \\${ -> \\\${
// .replaceAll(
// new RegExp(
// `${String(evenNumOfBackslashesRegExp.source)}(\`|\\\${)`,
// 'g',
// ),
// '\\$1',
// );

// // `...${'...$'}{...`
// // ^^^^
// if (
// nextCharacterIsOpeningCurlyBrace &&
// endsWithUnescapedDollarSign(escapedValue)
// ) {
// escapedValue = escapedValue.replaceAll(/\$$/g, '\\$');
// }

// if (escapedValue.length !== 0) {
// nextCharacterIsOpeningCurlyBrace = escapedValue.startsWith('{');
// }

// fixers.push(fixer => [fixer.replaceText(expression, escapedValue)]);
// } else if (isTemplateLiteral(expression)) {
// // Since we iterate from the last expression to the first,
// // a subsequent expression can tell the current expression
// // that it starts with {.
// //
// // `... ${`... $`}${'{...'} ...`
// // ^ ^ subsequent expression starts with {
// // current expression ends with a dollar sign,
// // so '$' + '{' === '${' (bad news for us).
// // Let's escape the dollar sign at the end.
// if (
// nextCharacterIsOpeningCurlyBrace &&
// endsWithUnescapedDollarSign(
// expression.quasis[expression.quasis.length - 1].value.raw,
// )
// ) {
// fixers.push(fixer => [
// fixer.replaceTextRange(
// [expression.range[1] - 2, expression.range[1] - 2],
// '\\',
// ),
// ]);
// }
// if (
// expression.quasis.length === 1 &&
// expression.quasis[0].value.raw.length !== 0
// ) {
// nextCharacterIsOpeningCurlyBrace =
// expression.quasis[0].value.raw.startsWith('{');
// }

// // Remove the beginning and trailing backtick characters.
// fixers.push(fixer => [
// fixer.removeRange([expression.range[0], expression.range[0] + 1]),
// fixer.removeRange([expression.range[1] - 1, expression.range[1]]),
// ]);
// } else {
// nextCharacterIsOpeningCurlyBrace = false;
// }

// // `... $${'{...'} ...`
// // ^^^^^
// if (
// nextCharacterIsOpeningCurlyBrace &&
// endsWithUnescapedDollarSign(prevQuasi.value.raw)
// ) {
// fixers.push(fixer => [
// fixer.replaceTextRange(
// [prevQuasi.range[1] - 3, prevQuasi.range[1] - 2],
// '\\$',
// ),
// ]);
// }

// context.report({
// node: expression,
// messageId: 'noUnnecessaryTemplateExpression',
// fix(fixer): TSESLint.RuleFix[] {
// return [
// // Remove the quasis' parts that are related to the current expression.
// fixer.removeRange([
// prevQuasi.range[1] - 2,
// expression.range[0],
// ]),
// fixer.removeRange([
// expression.range[1],
// nextQuasi.range[0] + 1,
// ]),

// ...fixers.flatMap(cb => cb(fixer)),
// ];
// },
// });
// }
},
};
},
});
Loading
Loading