非空断言运算符(后缀 !)
TypeScript 还具有一种特殊的语法,可以在不进行任何显式检查的情况下从类型中删除 null
和 undefined
。 在任何表达式之后写 !
实际上是一个类型断言,该值不是 null
或 undefined
:
TypeScript also has a special syntax for removing null
and undefined
from a type without doing any explicit checking. Writing !
after any expression is effectively a type assertion that the value isn't null
or undefined
:
function liveDangerously(x?: number | null) {
// No error
console.log(x!.toFixed());
}
ZAHI+0rh1Wv415t90pP0+EV+sL8w+p3TnG3oKSFNBQjcv1pR1leJAaB3MExrjAGHzHodgRAXKoes3lCnlzQVtQJOoYUqK55gJKhBYr8+32l6bWykii9IkzCEZj6cJmaUjCpsyQLn//h50are2VmcHfvAYclJ0Md8Ibiw3L+ziwwaG2637wTbfmlAMSxZEt8sph/MyxT1A4j1F4e5czArnNmHsEOiv13WvMkLAqqMr/BJ47iTMUrSY5bJias4jJNOHCEPaDd6jVUcdj3R08NfrKozyB1JhhDmdXXvmKVEffp+Z1y7vvlt5RpzQLWzp2A4CYOaRqKRcSBl6XZGxa+FzcqWr8grGaxtiA4t2Mz67T4AxmRTG77++UqHl2GiE1ALf2avVyXxSJP+GVsfxhaGLhQSz6xeudfWtHJpR58dPSq0F00UKqVxFinAl++JeXRPdAl2n0BCot4X1g7bWI/36RYYmvhCO+kQe4X+UBbhW5H2tBtZFVBVKAcP9CtP0p2Ykom53UoBoc7iqI+89UwZHRyDWWhx2ihGcXcbTxVMisHmtkhx/kAdnWZh02yUGiI4a1Av5NOZEmcGp/30nbgYag==