代码点读机 / TypeScript / !

! TypeScript · 符号

在值层面是把 true 翻成 false 的反转开关;在类型层面是"我保证这里不是 null/undefined"的拍胸脯。

怎么用

!值
值!.属性

小例子

let 在线 = !false;
let 元素 = document.getElementById("box")!;

运行结果

在线 是 true;类型检查结果:元素 被推断为非 null

提醒:运行时不做检查,若实际为 null/undefined 仍会崩溃

官方文档:https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#non-null-assertion-operator-postfix-

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← TypeScript全部词条