MST

星途 面试题库

面试题:TypeScript中如何将空值推到类型边界并处理

在TypeScript项目中,假设你有一个函数接收一个可能为null或undefined的值,你打算将空值推到类型边界处理,描述你会如何定义函数的参数类型以及在函数内部如何进行处理以确保空值被正确对待,用代码示例说明。
46.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 定义函数参数类型: 在TypeScript中,可以使用联合类型 | 来表示参数可能为 nullundefined。例如,如果函数接收一个字符串类型的值,但这个值可能为 nullundefined,可以这样定义参数类型:
    function processValue(value: string | null | undefined) {
        // 函数内部处理
    }
    
  2. 函数内部处理
    • 使用类型断言:如果确定值不为 nullundefined,可以使用类型断言。但要注意,使用不当可能导致运行时错误。
    function processValue(value: string | null | undefined) {
        if (value) {
            const strValue = value as string;
            console.log(strValue.length);
        }
    }
    
    • 使用可选链操作符(?.:这是一种更安全的处理方式,它允许在对象属性访问或函数调用时,如果对象为 nullundefined,表达式不会报错,而是返回 undefined
    function processValue(value: string | null | undefined) {
        const length = value?.length;
        console.log(length);
    }
    
    • 使用 NonNullable 类型NonNullable 类型可以从联合类型中排除 nullundefined
    function processValue(value: string | null | undefined) {
        const nonNullValue: NonNullable<typeof value> = value as NonNullable<typeof value>;
        console.log(nonNullValue.length);
    }
    
    不过在上述代码中,需要确保 value 不为 nullundefined,否则会有运行时错误,所以一般会结合 if 语句先进行判断。
    function processValue(value: string | null | undefined) {
        if (value) {
            const nonNullValue: NonNullable<typeof value> = value as NonNullable<typeof value>;
            console.log(nonNullValue.length);
        }
    }