如何基于TypeScript对象类型生成包含所有键的常量数组约束类型
TypeScript 数组与对象键完全匹配的类型定义
实现方案
推荐方案:泛型工厂函数
该方案使用简单,类型报错清晰,适配绝大多数场景:
type Fields = { countryCode: string; currency: string; otherFields: string; }; function defineAllowedFields<T extends readonly (keyof Fields)[]>( fields: keyof Fields extends T[number] ? T : never ) { return fields; }
校验效果
// 符合规则:包含所有Fields键、无额外字段 const allowedFields = defineAllowedFields(["countryCode", "currency", "otherFields"] as const); // 触发类型错误:缺少Fields的部分键 const allowedFields1 = defineAllowedFields(["countryCode"] as const); // 触发类型错误:包含Fields不存在的额外字段 const allowedFields2 = defineAllowedFields(["countryCode", "currency", "otherFields", "extraField"] as const);
纯类型定义方案
如果你需要直接声明SomeType类型,可以使用如下写法:
type FieldKeys = keyof Fields; type SomeType = readonly FieldKeys[] & (FieldKeys extends (typeof allowedFields)[number] ? typeof allowedFields : never);
内容的提问来源于stack exchange,提问作者Mauricio Dziedzinski
相关产品推荐
相关产品推荐

