本文へスキップ

prefer-nullish-coalescing

論理代入またはチェーンの代わりに、nullish 合体演算子を使用することを強制します。

🎨

拡張 "plugin:@typescript-eslint/"stylistic-type-checked" ESLint設定 で有効にすると、このルールが有効になります。

💡

このルールによって報告される問題の一部は、エディターの 候補.

によって手動で修正できます。

このルールを実行するには 型情報 が必要です。

?? nullish 合体ランタイム演算子を使用すると、nullまたはundefinedを処理する際にデフォルト値を提供できます。nullish 合体演算子は、元の値がnullまたはundefinedの場合にのみ合体するため、任意の偽の値で合体する論理OR演算子チェーン||に依存するよりもはるかに安全です。

このルールは、次を置き換えることを検討する必要がある場合に報告します。

  • ||演算子を??で置き換える
  • ||=演算子を??=で置き換える
注意

strictNullChecksが有効になっていない場合、このルールは期待通りに動作しません。

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-nullish-coalescing": "error"
}
};

Playgroundでこのルールを試してみてください ↗

オプション

このルールは次のオプションを受け入れます。

type Options = [
{
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean;
ignoreConditionalTests?: boolean;
ignoreMixedLogicalExpressions?: boolean;
ignorePrimitives?:
| {
bigint?: boolean;
boolean?: boolean;
number?: boolean;
string?: boolean;
[k: string]: unknown;
}
| true;
ignoreTernaryTests?: boolean;
},
];

const defaultOptions: Options = [
{
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
ignoreConditionalTests: false,
ignoreTernaryTests: false,
ignoreMixedLogicalExpressions: false,
ignorePrimitives: {
bigint: false,
boolean: false,
number: false,
string: false,
},
},
];

ignoreTernaryTests

このオプションをtrueに設定すると、nullish 合体演算子を使用して簡素化できる三項式はすべて無視されます。デフォルトではfalseに設定されています。

ignoreTernaryTests: falseの場合の不正なコードと、ignoreTernaryTests: trueの場合の正しいコード

const foo: any = 'bar';
foo !== undefined && foo !== null ? foo : 'a string';
foo === undefined || foo === null ? 'a string' : foo;
foo == undefined ? 'a string' : foo;
foo == null ? 'a string' : foo;

const foo: string | undefined = 'bar';
foo !== undefined ? foo : 'a string';
foo === undefined ? 'a string' : foo;

const foo: string | null = 'bar';
foo !== null ? foo : 'a string';
foo === null ? 'a string' : foo;
Playgroundで開く

ignoreTernaryTests: falseの場合の正しいコード

const foo: any = 'bar';
foo ?? 'a string';
foo ?? 'a string';
foo ?? 'a string';
foo ?? 'a string';

const foo: string | undefined = 'bar';
foo ?? 'a string';
foo ?? 'a string';

const foo: string | null = 'bar';
foo ?? 'a string';
foo ?? 'a string';
Playgroundで開く

ignoreConditionalTests

このオプションをtrueに設定すると、条件テスト内にあるケースはすべて無視されます。デフォルトではfalseに設定されています。

一般的に、条件テスト内の式は、論理OR演算子の偽のフォールスルー動作を意図的に使用しているため、演算子をnullish合体演算子に修正すると、バグが発生する可能性があります。

より厳格な条件テストを強制する場合は、strict-boolean-expressionsルールを使用することを検討してください。

ignoreConditionalTests: falseの場合の不正なコードと、ignoreConditionalTests: trueの場合の正しいコード

declare const a: string | null;
declare const b: string | null;

if (a || b) {
}
if ((a ||= b)) {
}
while (a || b) {}
while ((a ||= b)) {}
do {} while (a || b);
for (let i = 0; a || b; i += 1) {}
a || b ? true : false;
Playgroundで開く

ignoreConditionalTests: falseの場合の正しいコード

declare const a: string | null;
declare const b: string | null;

if (a ?? b) {
}
if ((a ??= b)) {
}
while (a ?? b) {}
while ((a ??= b)) {}
do {} while (a ?? b);
for (let i = 0; a ?? b; i += 1) {}
a ?? b ? true : false;
Playgroundで開く

ignoreMixedLogicalExpressions

このオプションをtrueに設定すると、混合論理式(&&付き)の一部である論理OR式はすべて無視されます。デフォルトではfalseに設定されています。

一般的に、混合論理式内の式は、論理OR演算子の偽のフォールスルー動作を意図的に使用しているため、演算子をnullish合体演算子に修正すると、バグが発生する可能性があります。

より厳格な条件テストを強制する場合は、strict-boolean-expressionsルールを使用することを検討してください。

ignoreMixedLogicalExpressions: falseの場合の不正なコードと、ignoreMixedLogicalExpressions: trueの場合の正しいコード

declare const a: string | null;
declare const b: string | null;
declare const c: string | null;
declare const d: string | null;

a || (b && c);
a ||= b && c;
(a && b) || c || d;
a || (b && c) || d;
a || (b && c && d);
Playgroundで開く

ignoreMixedLogicalExpressions: falseの場合の正しいコード

declare const a: string | null;
declare const b: string | null;
declare const c: string | null;
declare const d: string | null;

a ?? (b && c);
a ??= b && c;
(a && b) ?? c ?? d;
a ?? (b && c) ?? d;
a ?? (b && c && d);
Playgroundで開く

注記:この特定のケースのエラーは、修正ではなく候補として提示されます(下記参照)。これは、混合論理式内で||??に自動的に変換することが常に安全ではないためです。演算子の意図した優先順位を判断できないためです。設計上、??は、同じ式で&&または||と使用する場合、括弧が必要です。

ignorePrimitives

偽になる可能性のある特定のプリミティブ型のオペランドを含む式を無視する場合は、各プリミティブのブール値を含むオブジェクトを渡すことができます。

  • string: truestringnullまたはundefinedのユニオンを無視します(デフォルト:false)。
  • number: truenumbernullまたはundefinedのユニオンを無視します(デフォルト:false)。
  • bigint: truebigintnullまたはundefinedのユニオンを無視します(デフォルト:false)。
  • boolean: truebooleannullまたはundefinedのユニオンを無視します(デフォルト:false)。

ignorePrimitives: { string: false }の場合の不正なコードと、ignorePrimitives: { string: true }の場合の正しいコード

const foo: string | undefined = 'bar';
foo || 'a string';
Playgroundで開く

ignorePrimitives: { string: false }ignorePrimitives: { string: true }の両方の場合の正しいコード

const foo: string | undefined = 'bar';
foo ?? 'a string';
Playgroundで開く

また、すべてのプリミティブ型を無視する場合は、ignorePrimitives: trueに設定できます。これは、ignorePrimitives: { string: true, number: true, bigint: true, boolean: true }と同じです。

allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing

これをfalseに設定すると、tsconfig.jsonにコンパイラオプションstrictNullChecks(またはstrict)がtrueに設定されていないファイルごとに、ルールがエラーになります。

strictNullChecksがない場合、TypeScriptは本質的にundefinednullを型から消去します。つまり、このルールが変数の型を検査するときに、**変数がnullまたはundefinedになる可能性があることを判別できません**。これは、このルールを事実上無効にします。

コードベースの完全な型安全性を確保するには、strictNullChecksを使用する必要があります。

何らかの理由でstrictNullChecksをオンにできないが、このルールを使用したい場合は、このオプションを使用して許可できますが、コンパイラオプションがオフの場合、このルールの動作は未定義であることに注意してください。このオプションを使用している場合のバグレポートは受け付けません。

使用しない場合

TypeScript 3.7(またはそれ以降)を使用していない場合は、この演算子がサポートされていないため、このルールを使用できません。

参考資料


型チェック済みlintルールは従来のlintルールよりも強力ですが、型チェック済みlintingの設定も必要です。型チェック済みルールの有効化後にパフォーマンスの低下が発生する場合は、パフォーマンスに関するトラブルシューティングを参照してください。

リソース