跳到主要内容

TypeScript 中如何检查 null 和 undefined?

参考答案:

在 TypeScript 中,你可以使用 JavaScript 的常规方式来检查 nullundefined。通常,你可以使用 if 语句或者可选链(Optional Chaining)操作符(?.)来检查一个变量是否为 nullundefined

以下是一些例子:

  1. 使用 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');
}
  1. 使用可选链操作符(?.):
let variable: string | null | undefined = getSomeValueThatCouldBeNullOrUndefined();

console.log(variable?.length); // 如果 variable 是 null 或 undefined,这个表达式将返回 undefined,并且不会抛出错误
  1. 使用 !! 操作符将 nullundefined 转换为 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 的类型系统也可以帮助你避免一些 nullundefined 的问题。例如,你可以使用可选属性(?)和默认值来为变量或属性提供备选值。

let variable: string | undefined = getSomeValueThatCouldBeNullOrUndefined();

console.log(variable || 'default value'); // 如果 variable 是 undefined,将输出 'default value'

以上就是在 TypeScript 中检查 nullundefined 的一些常用方法。