📜  typescript assert non null - TypeScript (1)

📅  最后修改于: 2023-12-03 15:05:39.265000             🧑  作者: Mango

TypeScript: 断言非空

在 TypeScript 编程中,经常需要验证一个值不为 null 或 undefined。TypeScript 提供了非空断言操作符(!)来实现这一目的。

非空断言操作符

非空断言操作符(!)告诉编译器:断言当前值不为 null 或 undefined,允许你在编译时避免可能的运行时错误。

let myVar: string | undefined = undefined;
console.log(myVar.length); // error: Object is possibly 'undefined'.
console.log(myVar!.length); // ok

上面代码中的 myVar 被声明为可选字符串,是 undefined。如果直接使用 myVar.length,编译器会进行校验并提示:“Object is possibly 'undefined'”。

使用非空断言操作符(!)后,编译器将警告视为提示,不再提示。

需要注意的是,使用非空断言操作符要谨慎,因为如果值实际上是 null 或 undefined,会导致运行时错误。

非空断言操作符与类型断言

非空断言操作符与类型断言有些类似,但并不完全相同。

let myVar: string | undefined = undefined;
console.log((myVar as string).length); // error: Object is possibly 'undefined'.
console.log(myVar!.length); // ok

如上代码所示,使用类型断言将 myVar 强制转换为字符串,依旧不能避免编译器提示“Object is possibly 'undefined'”。

这是因为类型断言只是告诉编译器当前值的类型,并不改变当前值。而非空断言操作符则直接在编译期间断言该值不为 null 或 undefined。

总结

在 TypeScript 编程中,使用非空断言操作符可以避免编译器的 null 或 undefined 问题,但要保证值实际上不为 null 或 undefined。

值得注意的是,非空断言操作符和类型断言并不完全相同,使用时要注意区分。

我们应该谨慎使用非空断言操作符,以避免运行时错误。