no-unnecessary-type-conversion
当转换习惯用法不改变表达式的类型或值时,禁止使用它们。.
JavaScript 提供了几种常用的习惯用法来将值转换为特定类型:
¥JavaScript provides several commonly used idioms to convert values to a specific type:
-
原始类型强制转换(例如
Boolean(value)
、String(value)
):使用内 置原始函数¥Primitive coercion (e.g.
Boolean(value)
,String(value)
): using a built-in primitive function -
字符串连接(例如
value + ''
):将值转换为字符串¥String concatenation (e.g.
value + ''
): turning a value into a string -
一元强制转换(例如
+value
、!!value
):使用内置运算符¥Unary coercion (e.g.
+value
,!!value
): using a built-in operator -
许多类型都定义了
.toString()
方法。¥The
.toString()
method defined on many types
如果值已经是该类型,则无需进行这些转换。
¥These conversions are unnecessary if the value is already of that type.
- 扁平配置
- 旧版配置
export default tseslint.config({
rules: {
"@typescript-eslint/no-unnecessary-type-conversion": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-unnecessary-type-conversion": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ 错误
- ✅ 正确
String('123');
'123'.toString();
'' + '123';
'123' + '';
Number(123);
+123;
~~123;
Boolean(true);
!!true;
BigInt(BigInt(1));
let str = '123';
str += '';
Open in Playgroundfunction foo(bar: string | number) {
String(bar);
bar.toString();
'' + bar;
bar + '';
Number(bar);
+bar;
~~bar;
Boolean(bar);
!!bar;
BigInt(1);
bar += '';
}
Open in Playground选项
该规则不可配置。
何时不使用它
¥When Not To Use It
如果你不介意代码中存在无操作类型转换,则可以关闭此规则。如果你的类型不准确,则此规则可能会导致你删除实际需要的转换。
¥If you don't care about having no-op type conversions in your code, then you can turn off this rule. If you have types which are not accurate, then this rule might cause you to remove conversions that you actually do need.
相关
¥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.