no-base-to-string
要求僅對轉換成字串時會提供有用資訊的物件呼叫
.toString()
。
✅
延伸 "plugin:@typescript-eslint/recommended-type-checked"
中的 ESLint 組態 會啟用此規則。
💭
此規則需要 類型資訊 才能執行。
將 JavaScript 物件轉換成字串時(例如,使用 +
加到字串中,或是在 ${}
範本字面中),JavaScript 會呼叫該物件的 toString()
。預設的 Object .toString()
使用 "[object Object]"
格式,這通常不是所要的結果。此規則會針對不是原始型別而且未定義更有用的 .toString()
方法的轉換成字串值產生報告。
請注意,
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();
在新版中開啟// These types all have useful .toString()s
'Text' + true;
`Value: ${123}`;
`Arrays too: ${[1, 2, 3]}`;
(() => {}).toString();
// Defining a custom .toString class is considered acceptable
class CustomToString {
toString() {
return 'Hello, world!';
}
}
`Value: ${new CustomToString()}`;
const literalWithToString = {
toString: () => 'Hello, world!',
};
`Value: ${literalWithToString}`;
在新版中開啟選項
此規則接受以下選項
type Options = [
{
ignoredTypeNames?: string[];
},
];
const defaultOptions: Options = [
{ ignoredTypeNames: ['Error', 'RegExp', 'URL', 'URLSearchParams'] },
];
ignoredTypeNames
要略過的型別名稱的字串陣列,這對缺少 toString()
(但實際有 toString()
)的型別很有用。有某些型別在舊版本 TypeScript 中缺少 toString()
,例如 RegExp
、URL
、URLSearchParams
等。
以下範例使用預設選項 { ignoredTypeNames: ["RegExp"] }
時會被視為正確結果
`${/regex/}`;
'' + /regex/;
/regex/.toString();
let value = /regex/;
value.toString();
let text = `${value}`;
在新版中開啟何時不使用
如果您不在乎值中可能有 "[object Object]"
或不正確的型別轉換風險,那麼您就不需要這條規則。
相關
進階閱讀
經過型別檢查的程式碼檢查規則比傳統的程式碼檢查規則更強大,但需要設定經過型別檢查的程式碼檢查。如果您在啟用經過型別檢查的規則後遇到效能下降的情況,請參閱效能疑難排解。