typescript/strict-boolean-expressions 厳格
何をするか
論理式内に特定の型を許可しない。
なぜ問題なのか
論理値が期待される文脈で、論理型以外の型を使用することを禁止する。 boolean 型および never 型は常に許可される。追加で論理文脈において安全と見なされる型は、オプションにより設定可能である。
以下のノードがチェック対象となる:
!、&&、||演算子の引数- 条件式 (
cond ? x : y) の条件部 if、for、while、do-while文の条件部
例
このルールに対して不正なコードの例:
ts
const str = "hello";
if (str) {
console.log("string");
}
const num = 42;
if (num) {
console.log("number");
}
const obj = { foo: "bar" };
if (obj) {
console.log("object");
}
declare const maybeString: string | undefined;
if (maybeString) {
console.log(maybeString);
}
const result = str && num;
const ternary = str ? "yes" : "no";このルールに対して正しいコードの例:
ts
const str = "hello";
if (str !== "") {
console.log("string");
}
const num = 42;
if (num !== 0) {
console.log("number");
}
const obj = { foo: "bar" };
if (obj !== null) {
console.log("object");
}
declare const maybeString: string | undefined;
if (maybeString !== undefined) {
console.log(maybeString);
}
const bool = true;
if (bool) {
console.log("boolean");
}設定
このルールは以下のプロパティを持つ構成オブジェクトを受け入れます:
allowAny
type: boolean
default: false
論理文脈での any 型の使用を許可するかどうか。
allowNullableBoolean
type: boolean
default: false
論理文脈での可変的ブール型(例:boolean | null)の使用を許可するかどうか。
allowNullableEnum
type: boolean
default: false
論理文脈での可変的列挙型の使用を許可するかどうか。
allowNullableNumber
type: boolean
default: false
論理文脈での可変的数値型(例:number | null)の使用を許可するかどうか。
allowNullableObject
type: boolean
default: true
論理文脈での可変的オブジェクト型の使用を許可するかどうか。
allowNullableString
type: boolean
default: false
論理文脈での可変的文字列型(例:string | null)の使用を許可するかどうか。
allowNumber
type: boolean
default: true
論理文脈での数値型の使用を許可するかどうか(非ゼロ数のチェック)。
allowString
type: boolean
default: true
論理文脈での文字列型の使用を許可するかどうか(空でない文字列のチェック)。
使用方法
このルールを設定ファイルまたは CLI で有効化するには、次のように使用できます:
json
{
"rules": {
"typescript/strict-boolean-expressions": "error"
}
}bash
oxlint --type-aware --deny typescript/strict-boolean-expressions