后缀 ! 告诉编译器"我保证此值在这里不是 null 或 undefined"——在没有任何运行时检查的情况下从其类型中删除 null/undefined。
ts
function f(name?: ) {
.(name!.());
}
后缀 ! 告诉编译器"我保证此值在这里不是 null 或 undefined"——在没有任何运行时检查的情况下从其类型中删除 null/undefined。
function f(name?: ) {
.(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
这些中的每一个都处理缺失的情况,而不是对其进行断言。
! 是一个锐利的工具:它破坏了编译器试图为您提供的空值安全性。
偶尔是合理的(您拥有编译器缺乏的知识),但过度使用它会重新引入 strictNullChecks 防止的空值崩溃错误。
首先使用 ?.、?? 或显式守卫;仅当您能真正证明非空性时才使用 !。