Skip to content
← Back to rules

typescript/prefer-nullish-coalescing 厳格な

💭 This rule requires type information.
🛠️ An auto-fix is available for this rule.

何を実行するか

左側の引数が null または undefined である可能性がある場合、論理和演算子 (||) や条件式の代わりに ネルシスコエーリング演算子 (??) を使用することを強制します。

なぜ問題なのか

|| 演算子は、左側の値が任意の偽値(false0''nullundefinedNaN)の場合、右側の値を返します。そのため、nullundefined に対してデフォルト値を設定したいだけなのに、他の偽値でも動作してしまうことで予期しない振る舞いが生じる可能性があります。

ネルシスコエーリング演算子 (??) は、左側の値が null または undefined である場合にのみ右側の値を返すため、意図が明確になり、他の偽値によるバグを回避できます。

このルールに違反する不適切なコードの例

ts
declare const x: string | null;

// ?? がより適切なのに || を使っている
const foo = x || "default";

// ?? で簡略化可能だった三項演算子
const bar = x !== null && x !== undefined ? x : "default";
const baz = x != null ? x : "default";

// ?? で簡略化可能だった if 文
let value = "default";
if (x !== null && x !== undefined) {
  value = x;
}

このルールに準拠する適切なコードの例

ts
declare const x: string | null;

// ネルシスコエーリング演算子の使用
const foo = x ?? "default";

// 偽値としての動作が必要な場合、|| は問題ありません
declare const y: string;
const bar = y || "default";

// ブール値への型変換(`ignoreBooleanCoercion` で無視可能)
const bool = Boolean(x || y);

設定

このルールは以下のプロパティを持つ設定オブジェクトを受け入れます。

ignoreBooleanCoercion

type: boolean

default: false

Boolean コンストラクタの引数を無視するかどうか。

ignoreConditionalTests

type: boolean

default: true

条件式内にあるケースを無視するかどうか。

ignoreIfStatements

type: boolean

default: false

ネルシスコエーリング演算子を使用することで簡略化できる可能性のあるすべての if 文を無視するかどうか。

ignoreMixedLogicalExpressions

type: boolean

default: false

&& を含む混合論理式の一部である論理式(論理和)を無視するかどうか。

ignorePrimitives

type: boolean

ignorePrimitives が JSON で指定されるさまざまな方法を表します。次のいずれかになります:

  • true - すべてのプリミティブ型を無視
  • 無視するプリミティブを指定するオブジェクト

ignoreTernaryTests

type: boolean

default: false

ネルシスコエーリング演算子で簡略化可能なすべての三項演算子を無視するかどうか。

使い方

このルールを設定ファイルまたは CLI で有効化するには、次のように使用します:

json
{
  "rules": {
    "typescript/prefer-nullish-coalescing": "error"
  }
}
bash
oxlint --type-aware --deny typescript/prefer-nullish-coalescing

参照