MST

星途 面试题库

面试题:TypeScript 类型保护在泛型中的应用

实现一个泛型函数,该函数接收一个数组和一个类型保护函数作为参数。类型保护函数用于判断数组元素是否满足特定类型。泛型函数需要根据类型保护函数的结果,返回一个只包含满足特定类型元素的新数组。例如,假设有类型保护函数isString,泛型函数传入[1, 'a', 2, 'b']和isString后,应返回['a', 'b']。
28.4万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function filterByType<T, U extends T>(arr: T[], typeGuard: (element: T) => element is U): U[] {
    return arr.filter(typeGuard);
}

你可以这样使用:

function isString(s: any): s is string {
    return typeof s ==='string';
}
const result = filterByType([1, 'a', 2, 'b'], isString);
console.log(result);