TypeScript Null 与 Undefined
TypeScript 有一个强大的系统来处理 null 空值或 undefined 未定义的值。
默认情况下,
null 和 undefined 使被禁用的,可以通过将 strictNullChecks 设置为 true 来启用。当启用 strictNullChecks 时,当页其余部分都将使用。Types
null and undefined 都是基础类型,可以像其他类型一样使用,例如 string。
实例
let value: string | undefined | null = null;console.log(typeof value);value = 'hello';console.log(typeof value);value = undefined;console.log(typeof value);
当启用
strictNullChecks 时,除非将 undefined 显式地添加到类型中,否则 TypeScript 都需要设置值。可选链(Optional Chaining)
可选链 是一种 JavaScript 新特性,它经常与 TypeScript 的空处理配合使用。它可以使用紧凑的语法访问对象上的属性。在访问属性时,它可以与 ?. 运算符一起使用。
实例
interface House {sqft: number;yard?: {sqft: number;};}function printYardSize(house: House) {const yardSize = home.yard?.sqft;if (yardSize === undefined) {console.log('No yard');} else {console.log(`Yard is ${yardSize} sqft`);}}let home: House = {sqft: 500,};printYardSize(home); // Prints 'No yard'
空合并(Nullish Coalescence)
空合并 是另一个 JavaScript 新特性,它也可以很好地与 TypeScript 的空处理配合使用。它可以编写在处理 null 或 undefined 的表达式时指定回退。当表达式中可能出现其他 false 值,且这些值仍然是有效的时,它就非常有用了。它可以和 ?? 表达式中的运算符一起使用,类似于使用 && 运算符。
实例
function printMileage(mileage: number | null | undefined) {console.log(`Mileage: ${mileage ?? 'Not Available'}`);}printMileage(null); // Prints 'Mileage: Not Available'printMileage(0); // Prints 'Mileage: 0'
空值断言(Null Assertion)
TypeScript 的推断并不完善,有时一些有用的 null 或 undefined 值会被忽略。有一种简单的解决方法是是使用类型转换(casting),但是TypeScript 也提供了 ! 运算符作为一种更便捷的方式。
实例
function getValue(): string | undefined {return 'hello';}let value = getValue();console.log('value length: ' + value!.length);
就像类型转换(casting)一样,这可能是不安全,应谨慎使用。
数组边界处理
即使启用了 strictNullChecks,默认情况下 TypeScript 也会假定数组访问永远不会返回 undefined(除非 undefined 是数组类型的一部分)。
配置 noUncheckedIndexedAccess 可以解决这个问题。
实例
let array: number[] = [1, 2, 3];let value = array[0]; // with `noUncheckedIndexedAccess` this has the type `number | undefined`