MST
星途 面试题库

面试题:TypeScript静态类型检查中联合类型相关常见问题

在TypeScript中,假设你定义了一个联合类型 `let value: string | number;`,现在有一个函数 `printValue`,要求该函数接受这个联合类型作为参数,并根据传入值的类型进行不同的打印操作,同时要避免静态类型检查报错。请写出这个函数的实现。另外,如果在调用这个函数时传入了 `null`,如何在不改变原联合类型定义的前提下,通过类型断言或其他合法方式避免静态类型检查报错?
13.0万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function printValue(value: string | number) {
    if (typeof value ==='string') {
        console.log(`The string value is: ${value}`);
    } else if (typeof value === 'number') {
        console.log(`The number value is: ${value}`);
    }
}

// 调用函数并传入null时避免静态类型检查报错
let testValue: string | number | null = null;
// 使用类型断言
printValue(testValue as string | number);