typescript/no-unnecessary-template-expression 可疑
它做了什么
禁止不必要的模板表达式(插值),这些表达式可以被简化。
为什么这是个问题?
包含不必要的替换表达式的模板字面量会增加复杂性,但并未带来任何好处。静态字符串字面量或已经是字符串的表达式可以被简化。
注意:此规则不会标记没有替换表达式的模板字面量。例如,`hello` 是允许的,即使它可以写成 'hello'。
示例
此规则的 错误 代码示例:
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}`;此规则的 正确 代码示例:
ts
// 静态值已合并到模板中
const ab1 = `ab`;
// 包含非简单插值的模板
const name = "world";
const greeting = `Hello ${name}!`;
// 包含表达式的模板
const result = `Result: ${1 + 2}`;
// 简单字符串无需使用模板
const text = "a";
const wrappedText = text;
// 多行字符串是允许的
const multiline = `
Hello
world
`;如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"rules": {
"typescript/no-unnecessary-template-expression": "error"
}
}bash
oxlint --type-aware --deny typescript/no-unnecessary-template-expression