Skip to content
← Back to rules

typescript/no_extra_non_null_assertion 正しさ

This rule is turned on by default.
An auto-fix is available for this rule.

何を行うか

不要な非ヌル宣言(non-null assertion)を禁止します。

なぜこれは問題なのか

TypeScript の ! 非ヌル宣言演算子は、値の型に nullundefined が含まれないことを明示するために使われます。同じ値に対してこの演算子を複数回使用しても、効果はありません。

このルールに違反する誤ったコードの例:

ts
const foo: { bar: number } | null = null;
const bar = foo!!!.bar;
ts
function foo(bar: number | undefined) {
  const bar: number = bar!!!;
}
ts
function foo(bar?: { n: number }) {
  return bar!?.n;
}

このルールに準拠する正しいコードの例:

ts
const foo: { bar: number } | null = null;
const bar = foo!.bar;
ts
function foo(bar: number | undefined) {
  const bar: number = bar!;
}
ts
function foo(bar?: { n: number }) {
  return bar?.n;
}

使用方法

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

json
{
  "rules": {
    "typescript/no_extra_non_null_assertion": "error"
  }
}
bash
oxlint --deny typescript/no_extra_non_null_assertion

参照