在TypeScript中检查null和undefined
在 TypeScript 中,null 和 undefined 是两种不同的类型,TypeScript 提供了多种方法来检查这两种类型的值。以下是一些常用的方法和最佳实践。
1. 使用严格类型检查
TypeScript 提供了一个选项 strictNullChecks,当该选项开启时,null 和 undefined 不会被自动赋值给其他类型。开启该选项后,必须显式处理 null 和 undefined 的情况。
let value: string | null = null;
if (value !== null) {
console.log(value.length); // 安全访问
}
2. 使用类型保护
TypeScript 提供了类型保护功能,可以使用 typeof 操作符来检查变量的类型。
function processValue(value: string | null | undefined) {
if (typeof value === 'string') {
console.log(value.length); // 只有在 value 是 string 时才安全
} else {
console.log('value is null or undefined');
}
}
3. 使用可选链(Optional Chaining)
可选链操作符 ?. 允许我们在访问对象属性时避免因 null 或 undefined 而导致的错误。如果对象是 null 或 undefined,表达式会短路并返回 undefined。
interface User {
name?: string | null;
}
function getUserName(user: User) {
const nameLength = user.name?.length; // 如果 user.name 是 null 或 undefined,则 nameLength 为 undefined
console.log(nameLength);
}
4. 使用非空断言操作符
非空断言操作符 ! 告诉 TypeScript 编译器,某个值不会是 null 或 undefined。在使用时需要非常小心,因为如果值确实是 null 或 undefined,将导致运行时错误。
function getLength(value: string | null) {
return value!.length; // 断言 value 一定不为 null
}
5. 使用 nullish 合并运算符
nullish 合并运算符 ?? 用于提供一个默认值,当左侧的操作数为 null 或 undefined 时返回右侧的值。
function getUserAge(age: number | null | undefined) {
const validAge = age ?? 18; // 如果 age 是 null 或 undefined,则使用默认值 18
console.log(validAge);
}
6. 使用类型守卫
可以自定义类型守卫函数来处理 null 和 undefined 的检查,这样可以让代码更具可读性。
function isNotNull<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined;
}
function printValue(value: string | null | undefined) {
if (isNotNull(value)) {
console.log(value.toUpperCase());
}
}
7. 避免使用 null
在设计 API 和数据结构时,可以考虑用 undefined 来表示缺少值,而不是使用 null。这有助于减少 null 引起的潜在错误。
总结
在 TypeScript 中,null 和 undefined 的处理是一个重要的主题。通过使用严格的类型检查、类型保护、可选链、非空断言、nullish 合并运算符以及自定义类型守卫,我们可以有效地管理和检查这些值。务必根据项目需求,选择适合的方法来确保代码的安全性和可读性。