面试题答案
一键面试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);