能否基于对象字面量自动推导TypeScript类型?
TypeScript 对象字面量自动推导目标类型的实现方法
你可以通过TypeScript的字面量断言和高级类型工具实现从给定对象常量自动推导出目标接口与类型,避免重复定义。
问题场景回顾
给定如下对象常量:
const inputs = [ { name: "announcements", type: "list", subFields: [ { name: "copy", type: "string", defaultValue: "", }, { name: "buttonLabel", type: "string", defaultValue: "", }, { name: "buttonUrl", type: "url", defaultValue: "", }, ], }, ]
希望自动推导出:
interface Announcements { copy: string; buttonLabel: string; buttonUrl: string; } type AnnouncementList = Announcements[];
实现步骤
1. 保留完整字面量类型
首先给常量添加as const断言,让TypeScript推断出最精确的字面量类型(而非宽泛的string等类型):
const inputs = [ { name: "announcements", type: "list", subFields: [ { name: "copy", type: "string", defaultValue: "", }, { name: "buttonLabel", type: "string", defaultValue: "", }, { name: "buttonUrl", type: "url", defaultValue: "", }, ], }, ] as const;
2. 定义类型映射与提取工具
先定义字段类型到TS原生类型的映射,再通过类型工具提取目标结构:
// 映射字段type到TS类型,可按需扩展更多类型 type FieldTypeMap = { string: string; url: string; }; // 从subFields数组转换为对象类型 type SubFieldsToObject<T extends readonly { name: string; type: keyof FieldTypeMap }[]> = { [K in T[number]['name']]: FieldTypeMap[T[number] & { name: K }]['type'] }; // 从inputs数组中提取指定name的列表项的subFields类型 type GetListSubFields<T extends readonly { name: string; type: string; subFields: any }[], Name extends string> = Extract<T[number], { name: Name; type: "list" }>['subFields'];
3. 自动推导目标类型
基于上述工具,直接推导出需要的类型:
// 推导Announcements对象类型 type Announcements = SubFieldsToObject<GetListSubFields<typeof inputs, "announcements">>; // 推导AnnouncementList数组类型 type AnnouncementList = Announcements[];
验证效果
此时使用这两个类型时,TS会自动提供类型提示,且与手动定义的接口完全一致:
const list: AnnouncementList = [ { copy: "新公告", buttonLabel: "查看详情", buttonUrl: "/announcement" } ]; // 若字段类型错误或缺失,TS会直接抛出类型错误
内容的提问来源于stack exchange,提问作者pilotguy
相关产品推荐
相关产品推荐

