MST

星途 面试题库

面试题:TypeScript 复杂场景下函数重载与泛型的协同

假设你要实现一个数据处理函数,该函数接受一个字符串数组或者数字数组,根据数组类型的不同执行不同的操作。如果是字符串数组,对每个字符串进行大写转换并返回新数组;如果是数字数组,对每个数字进行平方运算并返回新数组。要求使用函数重载与泛型结合来实现,并且考虑类型安全和代码的可维护性。请写出完整的 TypeScript 代码。
17.4万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function processArray<T extends string | number>(arr: T[]): (string | number)[] {
    if (typeof arr[0] ==='string') {
        return arr.map(str => (str as string).toUpperCase()) as string[];
    } else {
        return arr.map(num => (num as number) ** 2) as number[];
    }
}

// 测试
const stringArray: string[] = ['hello', 'world'];
const result1 = processArray(stringArray);
console.log(result1);

const numberArray: number[] = [1, 2, 3];
const result2 = processArray(numberArray);
console.log(result2);