Skip to main content

no-base-to-string

Require .toString() to only be called on objects which provide useful information when stringified.

💭

该规则需要 类型信息 才能运行。


当对象转换为字符串时,例如当 + 添加到字符串或在 ${} 模板文本中时,JavaScript 将在对象上调用 toString()。 默认对象 .toString() 返回 "[object Object]",这通常不是预期的结果。 此规则报告非基元的字符串化值,并且不定义更有用的 .toString() 方法。

英:JavaScript will call toString() on an object when it is converted to a string, such as when + adding to a string or in ${} template literals. The default Object .toString() returns "[object Object]", which is often not what was intended. This rule reports on stringified values that aren't primitives and don't define a more useful .toString() method.

请注意,Function 提供了自己的 .toString(),用于返回函数的代码。 此规则不标记函数。

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-base-to-string": "error"
}
};
在线运行试试这个规则 ↗

示例

// Passing an object or class instance to string concatenation:
'' + {};

class MyClass {}
const value = new MyClass();
value + '';

// Interpolation and manual .toString() calls too:
`Value: ${value}`;
({}).toString();
Open in Playground

选项

ignoredTypeNames

要忽略的类型名称的字符串数组,这对于缺少 toString()(但实际上有 toString())的类型很有用。 旧版本 TypeScript 中缺少一些类型,例如 RegExpURLURLSearchParams 等。

英:A string array of type names to ignore, this is useful for types missing toString() (but actually has toString()). There are some types missing toString() in old version TypeScript, like RegExp, URL, URLSearchParams etc.

使用默认选项 { ignoredTypeNames: ["RegExp"] } 时,以下模式被认为是正确的:

英:The following patterns are considered correct with the default options { ignoredTypeNames: ["RegExp"] }:

`${/regex/}`;
'' + /regex/;
/regex/.toString();
let value = /regex/;
value.toString();
let text = `${value}`;
Open in Playground

何时不使用它

如果你不介意值中存在 "[object Object]" 或不正确类型强制的风险,那么你将不需要此规则。

英:If you don't mind a risk of "[object Object]" or incorrect type coercions in your values, then you will not need this rule.

进一步阅读

选项

该规则接受以下选项

type Options = [
{
ignoredTypeNames?: string[];
},
];

const defaultOptions: Options = [
{ ignoredTypeNames: ['Error', 'RegExp', 'URL', 'URLSearchParams'] },
];

资源