typescript/non-nullable-type-assertion-style 制限
何をするか
このルールは、非可変型に対して明示的な型キャストよりも非ヌルアサーション(!)を優先します。
なぜ問題なのか
値が null または undefined になりえないことが分かっている場合、非ヌルアサーション(!)または型アサーション(as Type)のどちらかを使うことができます。非ヌルアサーションはより簡潔であり、値が null/undefined でないことを明確に意図していることを伝えます。
例
このルールに対して誤りなコードの例:
ts
declare const value: string | null;
// 非ヌルアサーションの方が明確な場合でも型アサーションを使用
const result1 = value as string;
declare const maybe: number | undefined;
const result2 = maybe as number;
// 関数呼び出しでの使用
function takesString(s: string) {
console.log(s);
}
takesString(value as string);このルールに対して正しいコードの例:
ts
declare const value: string | null;
// 非可変型に対して非ヌルアサーションを使用
const result1 = value!;
declare const maybe: number | undefined;
const result2 = maybe!;
// 関数呼び出しでの使用
function takesString(s: string) {
console.log(s);
}
takesString(value!);
// 実際の型の変更が必要な場合は型アサーションも問題ありません
declare const unknown: unknown;
const str = unknown as string; // これは単に `null` を除去するのではなく、異なる型への変換です使い方
このルールを設定ファイルまたは CLI で有効化するには、次のようにします:
json
{
"rules": {
"typescript/non-nullable-type-assertion-style": "error"
}
}bash
oxlint --type-aware --deny typescript/non-nullable-type-assertion-style