後置の ! は「この値はここで null や undefined ではないと保証する」とコンパイラに伝え、実行時チェックなしでその型から null/undefined を取り除きます。
ts
function f(?: ) {
.(name!.());
}
後置の ! は「この値はここで null や undefined ではないと保証する」とコンパイラに伝え、実行時チェックなしでその型から null/undefined を取り除きます。
function f(?: ) {
.(name!.());
}
これは純粋にコンパイル時のアサーションです。as と同様、実行時の検証は一切行いません。間違っていればクラッシュします。
const el = document.getElementById("app")!; // assert non-null
el.innerHTML = "hi"; // 💥 runtime error if #app doesn't actually exist
// 1. You've logically guaranteed it, but the compiler can't see it
if (map.has(key)) map.get(key)!.doThing(); // has() proves get() isn't undefined
// 2. Class fields initialized outside the constructor (DI, lifecycle hooks)
class C { value!: string; } // definite assignment assertion
name?.toUpperCase(); // optional chaining — no crash, yields undefined
const x = name ?? "default"; // provide a fallback
if (name) name.toUpperCase(); // narrow with a real check
これらはいずれも、値が存在しないケースをアサーションで無視するのではなく、実際に処理します。
! は鋭い道具です。コンパイラが与えようとしている null 安全性を黙らせてしまいます。
コンパイラにはわからない知識を持っている場合など、たまに正当化されることもありますが、多用すると strictNullChecks が防いでいるはずの null クラッシュバグをまさに再導入してしまいます。
まず ?.、??、または明示的なガードを使い、非 null であることを本当に証明できる場合にのみ ! を使いましょう。