no-unsafe-unary-minus
Require unary negation to take a number.
💭
该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。
TypeScript 不会阻止你在数字以外的内容前添加减号:
¥TypeScript does not prevent you from putting a minus sign before things other than numbers:
const s = 'hello';
const x = -s; // x is NaN
此规则将一元 -
运算符限制为 number | bigint
。
¥This rule restricts the unary -
operator to number | bigint
.
- Flat Config
- Legacy Config
eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-unsafe-unary-minus": "error"
}
});
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-unsafe-unary-minus": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ Incorrect
- ✅ Correct
declare const a: string;
-a;
declare const b: {};
-b;
Open in Playground-42;
-42n;
declare const a: number;
-a;
declare const b: number;
-b;
declare const c: number | bigint;
-c;
declare const d: any;
-d;
declare const e: 1 | 2;
-e;
Open in Playground选项
该规则不可配置。
何时不使用它
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.
'## 资源'