MST

星途 面试题库

面试题:TypeScript函数类型注解与类型别名在泛型及条件类型中的深度结合

编写一个泛型函数,该函数接受一个数组和一个判断函数作为参数。判断函数根据数组元素类型有不同的判断逻辑(例如,如果元素是数字,判断是否大于10;如果是字符串,判断长度是否大于5)。请使用类型别名结合条件类型来定义判断函数类型,对泛型函数进行准确的类型注解,详细说明类型推导过程并编写完整代码。
22.5万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义一个类型别名,用于根据不同的元素类型确定判断函数的类型
type ElementCheckFunction<T> = T extends number
  ? (num: T) => boolean
    : T extends string
      ? (str: T) => boolean
        : never;

// 泛型函数,接受一个数组和一个判断函数作为参数
function filterArray<T>(arr: T[], checkFunction: ElementCheckFunction<T>): T[] {
  return arr.filter(checkFunction);
}

// 类型推导过程:
// 1. 当调用 filterArray 时,传入的数组类型会确定泛型 T 的类型。
// 2. 根据 T 的类型,ElementCheckFunction<T> 会通过条件类型确定具体的判断函数类型。
//    - 如果 T 是 number 类型,ElementCheckFunction<T> 就是 (num: number) => boolean。
//    - 如果 T 是 string 类型,ElementCheckFunction<T> 就是 (str: string) => boolean。
//    - 对于其他类型,ElementCheckFunction<T> 是 never,意味着这种情况不被支持。

// 示例使用
const numbers = [1, 15, 20];
const filteredNumbers = filterArray(numbers, (num) => num > 10);
console.log(filteredNumbers); 

const strings = ["hello", "world", "hi"];
const filteredStrings = filterArray(strings, (str) => str.length > 5);
console.log(filteredStrings);