Skip to main content

restrict-template-expressions

Enforce template literal expressions to be of string type.

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

JavaScript 会在字符串上下文中自动 将对象转换为字符串,例如使用 + 将其与字符串连接或使用 ${} 将其嵌入模板文字中时。对象的默认 toString() 方法使用格式 "[object Object]",这通常不是预期的。此规则报告包含替换表达式(也称为嵌入表达式或字符串插值)的模板文字,这些替换表达式是不必要的并且可以简化。

¥JavaScript automatically converts an object to a string in a string context, such as when concatenating it with a string using + or embedding it in a template literal using ${}. The default toString() method of objects uses the format "[object Object]", which is often not what was intended. This rule reports on values used in a template literal string that aren't strings, optionally allowing other data types that provide useful stringification results.

注意

此规则的默认设置有意不允许在模板文字中使用具有自定义 toString() 方法的对象,因为字符串化结果可能不方便用户使用。

¥The default settings of this rule intentionally do not allow objects with a custom toString() method to be used in template literals, because the stringification result may not be user-friendly.

例如,数组有一个自定义的 toString() 方法,它只在内部调用 join(),用逗号连接数组元素。这意味着 (1) 数组元素不一定会字符串化为有用的结果 (2) 逗号后面没有空格,导致结果对用户不友好。格式化数组的最佳方法是使用 Intl.ListFormat,它甚至支持在必要时添加 "and" 连词。如果你想在模板文字中使用此对象,则必须明确调用 object.toString(),或者打开 allowArray 选项以专门允许数组。no-base-to-string 规则可用于防止这种情况意外产生 "[object Object]"

¥For example, arrays have a custom toString() method, which only calls join() internally, which joins the array elements with commas. This means that (1) array elements are not necessarily stringified to useful results (2) the commas don't have spaces after them, making the result not user-friendly. The best way to format arrays is to use Intl.ListFormat, which even supports adding the "and" conjunction where necessary. You must explicitly call object.toString() if you want to use this object in a template literal, or turn on the allowArray option to specifically allow arrays. The no-base-to-string rule can be used to guard this case against producing "[object Object]" by accident.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/restrict-template-expressions": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

const arg1 = [1, 2];
const msg1 = `arg1 = ${arg1}`;

const arg2 = { name: 'Foo' };
const msg2 = `arg2 = ${arg2 || null}`;
Open in Playground

选项

This rule accepts the following options, and has more strict settings in the strict and strict-type-checked configs.

type Options = [
{
/** Types to allow in template expressions. */
allow?: (
| {
from: 'file';
name: [string, ...string[]] | string;
path?: string;
}
| {
from: 'lib';
name: [string, ...string[]] | string;
}
| {
from: 'package';
name: [string, ...string[]] | string;
package: string;
}
| string
)[];
/** Whether to allow `any` typed values in template expressions. */
allowAny?: boolean;
/** Whether to allow `array` typed values in template expressions. */
allowArray?: boolean;
/** Whether to allow `boolean` typed values in template expressions. */
allowBoolean?: boolean;
/** Whether to allow `never` typed values in template expressions. */
allowNever?: boolean;
/** Whether to allow `nullish` typed values in template expressions. */
allowNullish?: boolean;
/** Whether to allow `number` typed values in template expressions. */
allowNumber?: boolean;
/** Whether to allow `regexp` typed values in template expressions. */
allowRegExp?: boolean;
},
];

const defaultOptionsRecommended: Options = [
{
allow: [{ name: ['Error', 'URL', 'URLSearchParams'], from: 'lib' }],
allowAny: true,
allowBoolean: true,
allowNullish: true,
allowNumber: true,
allowRegExp: true,
},
];

// These options are merged on top of the recommended defaults
const defaultOptionsStrict: Options = [
{
allowAny: false,
allowBoolean: false,
allowNever: false,
allowNullish: false,
allowNumber: false,
allowRegExp: false,
},
];

¥Options

allowNumber

Whether to allow number typed values in template expressions. Default: true.

此规则使用 { allowNumber: true } 的其他正确代码示例:

¥Examples of additional correct code for this rule with { allowNumber: true }:

const arg = 123;
const msg1 = `arg = ${arg}`;
const msg2 = `arg = ${arg || 'zero'}`;
Open in Playground

此选项控制数字和 BigInt。

¥This option controls both numbers and BigInts.

如果你使用任何浮点数,我们建议避免使用此选项。尽管 ${1} 的计算结果为 '1',但 ${0.1 + 0.2} 的计算结果为 '0.30000000000000004'。考虑改用 .toFixed().toPrecision()

¥We recommend avoiding using this option if you use any floating point numbers. Although `${1}` evaluates to '1', `${0.1 + 0.2}` evaluates to '0.30000000000000004'. Consider using .toFixed() or .toPrecision() instead.

allowBoolean

Whether to allow boolean typed values in template expressions. Default: true.

此规则使用 { allowBoolean: true } 的其他正确代码示例:

¥Examples of additional correct code for this rule with { allowBoolean: true }:

const arg = true;
const msg1 = `arg = ${arg}`;
const msg2 = `arg = ${arg || 'not truthy'}`;
Open in Playground

allowAny

Whether to allow any typed values in template expressions. Default: true.

此规则使用 { allowAny: true } 的其他正确代码示例:

¥Examples of additional correct code for this rule with { allowAny: true }:

const user = JSON.parse('{ "name": "foo" }');
const msg1 = `arg = ${user.name}`;
const msg2 = `arg = ${user.name || 'the user with no name'}`;
Open in Playground

allowNullish

Whether to allow nullish typed values in template expressions. Default: true.

此规则使用 { allowNullish: true } 的其他正确代码示例:

¥Examples of additional correct code for this rule with { allowNullish: true }:

const arg = condition ? 'ok' : null;
const msg1 = `arg = ${arg}`;
Open in Playground

allowRegExp

Whether to allow regexp typed values in template expressions. Default: true.

此规则使用 { allowRegExp: true } 的其他正确代码示例:

¥Examples of additional correct code for this rule with { allowRegExp: true }:

const arg = new RegExp('foo');
const msg1 = `arg = ${arg}`;
Open in Playground
const arg = /foo/;
const msg1 = `arg = ${arg}`;
Open in Playground

allowNever

Whether to allow never typed values in template expressions. Default: false.

此规则使用 { allowNever: true } 的其他正确代码示例:

¥Examples of additional correct code for this rule with { allowNever: true }:

const arg = 'something';
const msg1 = typeof arg === 'string' ? arg : `arg = ${arg}`;
Open in Playground

allowArray

Whether to allow array typed values in template expressions. Default: false.

此规则使用 { allowArray: true } 的其他正确代码示例:

¥Examples of additional correct code for this rule with { allowArray: true }:

const arg = ['foo', 'bar'];
const msg1 = `arg = ${arg}`;
Open in Playground

allow

Types to allow in template expressions. Default: [{"name":["Error","URL","URLSearchParams"],"from":"lib"}].

此选项采用共享 TypeOrValueSpecifier 格式

¥This option takes the shared TypeOrValueSpecifier format.

此规则使用默认选项 { allow: [{ from: 'lib', name: 'Error' }, { from: 'lib', name: 'URL' }, { from: 'lib', name: 'URLSearchParams' }] } 的其他正确代码示例:

¥Examples of additional correct code for this rule with the default option { allow: [{ from: 'lib', name: 'Error' }, { from: 'lib', name: 'URL' }, { from: 'lib', name: 'URLSearchParams' }] }:

const error = new Error();
const msg1 = `arg = ${error}`;
Open in Playground

何时不使用它

¥When Not To Use It

如果你不担心模板文本中的非字符串值被错误地字符串化,那么你可能不需要此规则。

¥If you're not worried about incorrectly stringifying non-string values in template literals, then you likely don't need this rule.

相关

¥Related To


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

'## 资源'