乐闻世界logo
搜索文章和话题

如何在 TypeScript 中检查变量是否为 null 或未定义?

2 个月前提问
2 个月前修改
浏览次数25

1个答案

1

在TypeScript中,检查一个变量是否为nullundefined可以通过几种方法实现。下面我将详细介绍几种常用的方法:

1. 使用 == null 检查

在JavaScript和TypeScript中,使用双等号 == 可以同时检查变量是否为 nullundefined。这是因为 null == undefined 在JavaScript中是成立的。这种方法简单且易于理解。

typescript
function isNullOrUndefined(value: any): boolean { return value == null; } const a: any = null; const b: any = undefined; const c: any = 5; console.log(isNullOrUndefined(a)); // 输出:true console.log(isNullOrUndefined(b)); // 输出:true console.log(isNullOrUndefined(c)); // 输出:false

2. 使用严格等于 === 检查

如果想要分别明确检查 nullundefined,可以使用严格等于 ===。这种方式严格区分了 nullundefined,不会进行类型转换。

typescript
function isNull(value: any): boolean { return value === null; } function isUndefined(value: any): boolean { return value === undefined; } const a: any = null; const b: any = undefined; const c: any = 5; console.log(isNull(a)); // 输出:true console.log(isNull(b)); // 输出:false console.log(isUndefined(b)); // 输出:true console.log(isUndefined(c)); // 输出:false

3. 使用逻辑或操作符 || 提供默认值

有时,我们不仅要检查变量是否为 nullundefined,还需要在这种情况下提供一个默认值。这可以通过逻辑或操作符 || 实现。

typescript
function getValueOrDefault(value: any, defaultValue: any): any { return value == null ? defaultValue : value; } const a: any = null; const b: any = undefined; const c: any = 5; console.log(getValueOrDefault(a, 10)); // 输出:10 console.log(getValueOrDefault(b, 10)); // 输出:10 console.log(getValueOrDefault(c, 10)); // 输出:5

4. 使用可选链(Optional Chaining)

TypeScript 3.7 引入了可选链,它允许我们安全地访问深层嵌套的属性,而不必显式地检查每一层是否为 nullundefined

typescript
type User = { name: string; address?: { street?: string; city?: string; }; }; function getAddress(user: User): string | undefined { return user.address?.street; } const userWithAddress: User = { name: "Alice", address: { street: "123 Main St" } }; const userWithoutAddress: User = { name: "Bob" }; console.log(getAddress(userWithAddress)); // 输出:"123 Main St" console.log(getAddress(userWithoutAddress)); // 输出:undefined

这些方法每一种都有其适用场景,具体使用哪一种取决于你的具体需求和上下文环境。

2024年7月29日 13:40 回复

你的答案