在TypeScript中,null和undefined有各自的类型分别是null和undefined。检查变量是否为null或undefined是常见的需求,尤其是在处理外部数据或复杂的逻辑时。TypeScript提供了几种方式来检查null和undefined。
严格的空检查(Strict Null Checks)
在TypeScript中启用严格的空检查(通过tsconfig.json中的"strictNullChecks": true选项)是处理null和undefined的首选方法。启用该选项后,TypeScript会将null和undefined视为其它类型(如string、number等)的有效值,这迫使你在使用可能为null或undefined的变量之前显式地检查它们。
使用类型保护进行检查
你可以使用简单的if语句来检查一个值是否为null或undefined,这在TypeScript中被称为类型保护:
function doSomething(x: string | null) {
if (x === null) {
// x is null here
console.log("x is null");
} else {
// x is string here
console.log(x.toUpperCase()); // OK
}
}
同样,对于undefined的检查
function doSomethingElse(x: string | undefined) {
if (x === undefined) {
// x is undefined here
console.log("x is undefined");
} else {
// x is string here
console.log(x.toUpperCase()); // OK
}
}
使用非空断言操作符
如果你确定一个值不会是null或undefined,但类型系统不这么认为,你可以使用非空断言操作符!来告诉TypeScript该值一定不为null或undefined:
function doAnotherThing(x: string | null) {
console.log(x!.toUpperCase()); // 使用 ! 断言x不为null
}
请注意,过度使用非空断言操作符可能会隐藏潜在的问题,应当谨慎使用。
可选链(Optional Chaining)
TypeScript 3.7引入了可选链(?.),它允许你安全地访问深层嵌套的属性,而不必显式检查每一级是否为null或undefined:
type User = {
info?: {
name?: string;
};
};
const user: User = {};
const name = user.info?.name; // 如果user.info是undefined,则name也是undefined,而不是抛出错误
空值合并操作符
空值合并操作符(??)允许你为null或undefined的值提供一个默认值:
const name = user.info?.name ?? "default name";
在这个例子中,如果user.info?.name的结果是null或undefined,则name将被赋值为"default name"。
这些工具和技巧可以帮助你在TypeScript中更安全、更有效地处理null和undefined。
306

被折叠的 条评论
为什么被折叠?



