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; // any に対して不安全

declare const str: string;
const result2 = -str; // string に対して不安全

declare const bool: boolean;
const result3 = -bool; // boolean に対して不安全

declare const obj: object;
const result4 = -obj; // object に対して不安全

declare const arr: any[];
const result5 = -arr; // array に対して不安全

このルールに対する正しい例:

ts
declare const num: number;
const result1 = -num; // 安全

declare const bigint: bigint;
const result2 = -bigint; // 安全

const literal = -42; // 安全

const bigintLiteral = -42n; // 安全

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

// 必要に応じて最初に数値に変換する
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

参照