TypeScript 中如何检查 null 和 undefined?

参考回答

在 TypeScript 中,检查 nullundefined 是确保代码健壮性的重要部分。TypeScript 提供了多种方式来检查和处理 nullundefined,包括使用严格的类型检查、类型保护和空值合并操作符等。

详细讲解与拓展

  1. 使用严格类型检查(strictNullChecks
    • TypeScript 中的 strictNullChecks 选项决定了是否对 nullundefined 进行严格检查。启用该选项后,nullundefined 将被视为不同于任何其他类型,这意味着不能将 nullundefined 赋值给其他类型(除非显式声明允许)。

    tsconfig.json 中启用 strictNullChecks

    {
     "compilerOptions": {
       "strictNullChecks": true
     }
    }
    

    启用严格类型检查后:

    let value: string = null;  // 错误:不能将 null 赋值给 string 类型
    

    在默认的情况下(strictNullChecks: false),nullundefined 可以赋值给任何类型。

  2. 显式检查 nullundefined

    • 在代码中,可以使用 if 语句来显式检查 nullundefined,以防止运行时错误。

    示例:

    let value: string | null = null;
    
    if (value !== null && value !== undefined) {
       console.log(value.length);  // 安全地使用 value
    }
    

    这个检查确保 value 在使用前既不是 null 也不是 undefined

  3. 类型保护(Type Guards)

    • TypeScript 提供了类型保护机制,可以帮助在运行时确保变量的类型安全。通过使用 typeofinstanceof 等操作符,可以将变量缩小为更具体的类型。

    示例(使用 typeof 进行类型保护):

    let value: string | null = null;
    
    if (typeof value === "string") {
       console.log(value.length);  // 只有在 value 是 string 类型时才会执行
    }
    
  4. 空值合并操作符(??
    • TypeScript 允许使用空值合并操作符(??)来提供默认值。该操作符会返回左侧的值,除非左侧的值是 nullundefined,此时会返回右侧的值。

    示例:

    let value: string | null = null;
    let result = value ?? "Default Value";  // 如果 value 是 null 或 undefined,使用默认值
    console.log(result);  // 输出: "Default Value"
    
  5. 可选链操作符(?.
    • 可选链操作符(?.)使得在访问嵌套对象属性时,如果某个中间值为 nullundefined,则不会抛出错误,而是返回 undefined

    示例:

    let user: { name?: string } | null = null;
    let userName = user?.name;  // 如果 user 为 null,userName 会是 undefined,而不是抛出错误
    console.log(userName);  // 输出: undefined
    
  6. 显式类型声明(nullundefined
    • TypeScript 默认会将 nullundefined 视为特殊类型。如果你希望 nullundefined 能够赋值给其他类型的变量,可以使用联合类型来明确允许这两种情况。

    示例:

    let value: string | null = null;
    value = "Hello";  // 合法,value 可以是 string 或 null
    

总结
在 TypeScript 中,检查 nullundefined 主要依赖于严格的类型检查、显式的类型保护、空值合并操作符和可选链操作符等工具。启用 strictNullChecks 选项后,nullundefined 会被视为不同类型,避免了许多潜在的运行时错误。通过使用类型保护和空值合并操作符,开发者能够更加安全和清晰地处理 nullundefined

发表评论

后才能评论