TypeScript:非空断言操作符(!.)与 可选链操作符(?.)区别 作者:马育民 • 2025-12-18 11:45 • 阅读:10002 # 区别 | 语法 | 作用 | 运行时行为 | |--------|---------------------------------------|-------------------------------------| | `!.` | 断言非空,消除编译警告 | 若值为空,直接报错 | | `?.` | 安全访问,避免运行时报错 | 若值为空,返回 `undefined` | 示例对比: ```typescript let obj: { name: string } | undefined; // !.:断言非空,编译通过但运行时报错 // console.log(obj!.name); // ?.:安全访问,运行时返回 undefined,无报错 console.log(obj?.name); // undefined ``` 原文出处:http://www.malaoshi.top/show_1GW2Qc8i3Wfc.html