TypeScript 中如何检查 null 和 undefined?
参考答案:
在 TypeScript 中,你可以使用 JavaScript 的常规方式来检查 null
和 undefined
。通常,你可以使用 if
语句或者可选链(Optional Chaining)操作符(?.
)来检查一个变量是否为 null
或 undefined
。
以下是一些例子:
- 使用
if
语句检查:
let variable: string | null | undefined = getSomeValueThatCouldBeNullOrUndefined();
if (variable === null || variable === undefined) {
console.log('variable is null or undefined');
} else {
console.log('variable is defined and not null');
}
- 使用可选链操作符(
?.
):
let variable: string | null | undefined = getSomeValueThatCouldBeNullOrUndefined();
console.log(variable?.length); // 如果 variable 是 null 或 undefined,这个表达式将返回 undefined,并且不会抛出错误
- 使用
!!
操作符将null
和undefined
转换为false
,其他值转换为true
:
let variable: string | null | undefined = getSomeValueThatCouldBeNullOrUndefined();
if (!!variable) {
console.log('variable is defined and not null');
} else {
console.log('variable is null or undefined');
}
请注意,TypeScript 的类型系统也可以帮助你避免一些 null
和 undefined
的问题。例如,你可以使用可选属性(?
)和默认值来为变量或属性提供备选值。
let variable: string | undefined = getSomeValueThatCouldBeNullOrUndefined();
console.log(variable || 'default value'); // 如果 variable 是 undefined,将输出 'default value'
以上就是在 TypeScript 中检查 null
和 undefined
的一些常用方法。