MST
星途 面试题库

面试题:TypeScript 类型别名、并集与交集在泛型编程中的深度运用

编写一个泛型函数 `combineData`,它接收两个参数,第一个参数 `data1` 可以是字符串数组或者数字数组(使用类型别名和并集定义),第二个参数 `data2` 可以是布尔值数组或者字符串数组(同样使用类型别名和并集定义)。该函数要返回一个新数组,新数组元素类型是 `data1` 和 `data2` 元素类型的交集(如果存在)。如果交集为空,返回 `null`。请使用类型别名、并集、交集以及泛型来实现该函数,并进行必要的类型检查和处理。
33.7万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义类型别名
type Data1Type = string[] | number[];
type Data2Type = boolean[] | string[];

function combineData<T, U>(data1: T, data2: U): (T extends any[] ? (U extends any[] ? (T[number] & U[number])[] : null) : null) {
    // 类型检查
    if (!Array.isArray(data1) ||!Array.isArray(data2)) {
        return null;
    }
    // 检查交集类型
    if ((Array.isArray(data1) && Array.isArray(data2)) && ((data1.every((item) => typeof item ==='string') && data2.every((item) => typeof item ==='string')))) {
        return data1.filter((item, index) => data2.includes(item)) as (T[number] & U[number])[];
    }
    return null;
}