MST

星途 面试题库

面试题:TypeScript 中字面量类型、类型守卫与泛型的综合运用

编写一个通用的函数 `processValue`,它接受两个参数,第一个参数是一个字面量类型的数组(例如 `['a', 'b', 'c']`),第二个参数是一个回调函数。回调函数的参数类型根据第一个参数数组中的字面量类型确定。例如,如果数组是 `['number', 'boolean']`,那么回调函数应该接收两个参数,第一个参数是 `number` 类型,第二个参数是 `boolean` 类型。在 `processValue` 函数内部,使用类型守卫确保传入的回调函数参数类型正确,并执行回调函数。请实现该 `processValue` 函数,并编写相应的测试代码验证其正确性。
26.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function processValue<T extends string[]>(arr: T, callback: (...args: { [K in keyof T]: T[K] extends 'number'? number : T[K] extends 'boolean'? boolean : T[K] } ) => void) {
    const types: string[] = arr;
    const args: any[] = [];
    types.forEach(type => {
        if (type === 'number') {
            args.push(1);
        } else if (type === 'boolean') {
            args.push(true);
        } else {
            args.push(type);
        }
    });
    callback(...args);
}

// 测试代码
processValue(['number', 'boolean'], (num: number, bool: boolean) => {
    console.log(`数字: ${num}, 布尔值: ${bool}`);
});

processValue(['string', 'number'], (str: string, num: number) => {
    console.log(`字符串: ${str}, 数字: ${num}`);
});