Skip to content
← Back to rules

typescript/no-unsafe-unary-minus 正确性

This rule is turned on by default when type-aware linting is enabled.
💭 This rule requires type information.

它的作用

此规则禁止对非 number | bigint 类型的值使用一元减号运算符。

为什么这是错误的?

一元减号运算符应仅用于数值类型。对其他类型使用它可能导致意外行为,这是由于 JavaScript 的类型强制规则所致。

示例

此规则的 错误 代码示例:

ts
declare const value: any;
const result1 = -value; // unsafe on any

declare const str: string;
const result2 = -str; // unsafe on string

declare const bool: boolean;
const result3 = -bool; // unsafe on boolean

declare const obj: object;
const result4 = -obj; // unsafe on object

declare const arr: any[];
const result5 = -arr; // unsafe on array

此规则的 正确 代码示例:

ts
declare const num: number;
const result1 = -num; // safe

declare const bigint: bigint;
const result2 = -bigint; // safe

const literal = -42; // safe

const bigintLiteral = -42n; // safe

declare const union: number | bigint;
const result3 = -union; // safe

// 如需转换,请先转为 number
declare const str: string;
const result4 = -Number(str); // 安全转换

如何使用

通过配置文件或 CLI 启用 此规则,可以使用以下方式:

json
{
  "rules": {
    "typescript/no-unsafe-unary-minus": "error"
  }
}
bash
oxlint --type-aware --deny typescript/no-unsafe-unary-minus

参考资料