Skip to main content

no-base-to-string

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

💭

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

JavaScript 会在对象转换为字符串时调用 toString(),例如与字符串连接时(expr + '')、插入模板字面量时(${expr})或作为参数传递给 String 构造函数时(String(expr))。默认对象 .toString()toLocaleString() 使用格式 "[object Object]",这通常不是预期的。此规则报告 .toString()toLocaleString() 或 指令的使用情况。

¥JavaScript will call toString() on an object when it is converted to a string, such as when concatenated with a string (expr + ''), when interpolated into template literals (${expr}), or when passed as an argument to the String constructor (String(expr)). The default Object .toString() and toLocaleString() use the format "[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() or toLocaleString() method.

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

¥Note that Function provides its own .toString() and toLocaleString() that return the function's code. Functions are not flagged by this rule.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-base-to-string": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

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

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

// Interpolation and manual .toString() and `toLocaleString()` calls too:
`Value: ${value}`;
String({});
({}).toString();
({}).toLocaleString();

// Stringifying objects or instances in an array with the `Array.prototype.join`.
[{}, new MyClass()].join('');
Open in Playground

备择方案

¥Alternatives

当你想要将非原始内容转换为字符串以进行日志记录、调试等时,请考虑使用 JSON.stringify

¥Consider using JSON.stringify when you want to convert non-primitive things to string for logging, debugging, etc.

declare const o: object;
const errorMessage = 'Found unexpected value: ' + JSON.stringify(o);

选项

该规则接受以下选项:

type Options = [
{
/** Stringified regular expressions of type names to ignore. */
ignoredTypeNames?: string[];
},
];

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

¥Options

ignoredTypeNames

Stringified regular expressions of type names to ignore. Default: ["Error","RegExp","URL","URLSearchParams"].

这对于缺少 toString()toLocaleString()(但实际上有 toString()toLocaleString())的类型很有用。在旧版本的 TypeScript 中,有些类型缺少 toString()toLocaleString(),例如 RegExpURLURLSearchParams 等。

¥This is useful for types missing toString() or toLocaleString() (but actually has toString() or toLocaleString()). There are some types missing toString() or toLocaleString() in old versions of 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}`;
String(/regex/);
Open in Playground

何时不使用它

¥When Not To Use It

如果你不介意值中存在 "[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.

相关

¥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.

¥Further Reading

资源