MST

星途 面试题库

面试题:TypeScript类型守卫与类型缩小在泛型中的深度实践

实现一个泛型函数,该函数接收一个数组,数组元素是一个联合类型。在函数内部,通过类型守卫和类型缩小,将数组中特定类型的元素提取出来,并返回。要求该函数能够适用于不同的联合类型,且提取类型作为参数传入函数。例如,传入 [1, 'a', 2, 'b'] 和 string 类型,返回 ['a', 'b']。
10.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function extractType<T, U extends T>(arr: T[], type: new () => U): U[] {
    return arr.filter((item): item is U => item instanceof type) as U[];
}

上述代码定义了一个泛型函数 extractType,它接收一个数组 arr 和一个构造函数 type。通过 filter 方法和类型守卫 item instanceof type 来过滤出符合特定类型 U 的元素,并返回一个只包含该类型元素的数组。使用时可以像这样调用:

const result = extractType([1, 'a', 2, 'b'], String);
console.log(result); 

这里将 [1, 'a', 2, 'b'] 数组中 string 类型的元素提取出来。

如果你使用的是 JavaScript(没有类型系统),实现思路如下:

function extractType(arr, targetType) {
    return arr.filter(item => typeof item === targetType);
}
const result = extractType([1, 'a', 2, 'b'],'string');
console.log(result); 

但 JavaScript 这种方式不如 TypeScript 严谨,因为它只是简单通过 typeof 判断,无法处理更复杂的类型判断,比如自定义对象类型等。