区别
| 语法 | 作用 | 运行时行为 |
|---|---|---|
!. |
断言非空,消除编译警告 | 若值为空,直接报错 |
?. |
安全访问,避免运行时报错 | 若值为空,返回 undefined |
示例对比:
let obj: { name: string } | undefined;
// !.:断言非空,编译通过但运行时报错
// console.log(obj!.name);
// ?.:安全访问,运行时返回 undefined,无报错
console.log(obj?.name); // undefined