MST

星途 面试题库

面试题:TypeScript元编程实现动态对象构建

使用TypeScript的元编程技术(如类型映射、条件类型等),编写一个通用函数`buildObject`,该函数接受一个对象类型作为参数,并返回一个新的对象,新对象的属性值根据传入的类型动态生成,例如传入`{a: string, b: number}`,生成的对象可能是`{a: 'default string', b: 0}`,要求尽可能地利用类型系统确保生成对象的类型正确性。
17.7万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
type BuildObject<T extends Record<string, unknown>> = {
    [K in keyof T]: T[K] extends string? 'default string' : T[K] extends number? 0 : never;
};

function buildObject<T extends Record<string, unknown>>(type: T): BuildObject<T> {
    const result = {} as BuildObject<T>;
    for (const key in type) {
        if (Object.prototype.hasOwnProperty.call(type, key)) {
            if (typeof type[key] ==='string') {
                result[key as keyof BuildObject<T>] = 'default string' as any;
            } else if (typeof type[key] === 'number') {
                result[key as keyof BuildObject<T>] = 0 as any;
            }
        }
    }
    return result;
}