// 定义一个类型别名,用于根据不同的元素类型确定判断函数的类型
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);