MST

星途 面试题库

面试题:TypeScript 联合类型类型保护中的类型缩小技巧

假设有一个联合类型 `type MyUnion = string | number | null`,编写一个函数,接收这个联合类型作为参数,通过类型保护实现当参数为 `string` 类型时返回其长度,为 `number` 类型时返回其平方,为 `null` 时返回 `0`。同时,说明在这个过程中使用了哪些类型缩小技巧,为什么这些技巧有效。
35.6万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function handleMyUnion(input: MyUnion): number {
    if (typeof input ==='string') {
        return input.length;
    } else if (typeof input === 'number') {
        return input * input;
    } else {
        return 0;
    }
}

使用的类型缩小技巧及原因

  1. typeof 类型判断
    • 使用 typeof input ==='string'typeof input === 'number' 来判断参数的类型。这是因为 typeof 操作符在 TypeScript 中不仅是运行时检查,也能在类型检查阶段起作用。TypeScript 编译器知道 typeof 操作符返回的结果,所以当 typeof input ==='string' 成立时,在这个分支内,TypeScript 能够将 input 的类型缩小为 string,同理对于 number 分支。这使得我们可以安全地调用 string 类型的 length 属性和对 number 类型进行乘法运算。
  2. 逻辑判断分支
    • 通过 if - else if - else 的逻辑分支结构,在每个分支中根据类型检查结果进行不同的操作。当 typeof input ==='string' 不成立进入下一个 else if 分支时,input 的类型已经排除了 string,只剩下 numbernull,所以 typeof input === 'number' 能进一步缩小类型。最后的 else 分支就可以确定 inputnull 类型。这种逐步排除的方式有效缩小了 input 在每个分支内的类型范围,保证了类型安全。