如何用TypeScript定义含关联字段约束的对象类型?
TypeScript中如何定义类型,确保
fieldValues的键全为fields数组对象的id值? 我们需要为如下结构的对象定义TypeScript类型,保证fieldValues的所有键都严格对应fields数组里每个对象的id属性值:
示例对象:
const x = { fields: [ { id: "field1", type: "string" }, { id: "field2", type: "number" }, { id: "my_field", type: "email" } ], fieldValues: { field1: "John", field2: "John", my_field: "@" } }
以下是两种尝试方案:
方案一
该方案可正常生效,但需要给每个id添加as const修饰符,且fields与fieldValues必须分开定义:
const fields = [ { id: "bid" as const, c: "d" }, { id: "cid" as const, c: "e" } ] const fieldValues: Record<typeof fields[number]["id"], any> = { bid: "d", cid: "e", // 下一行会报错,符合预期! a: "f" }
方案二
该方案接近理想效果,但Test类型需要显式声明ID列表,使用起来不够便捷:
interface FieldType { type: "string" | "number" | "email" } type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType extends readonly (infer ElementType)[] ? ElementType : never type Fields<T extends string[]> = readonly (FieldType & { id: ArrayElement<T> })[] interface Test<T extends string[]> { fields: Fields<T> fieldValues: Record<ArrayElement<Fields<T>>["id"], any> } const x: Test<["field1", "field2", "my_field"]> = { fields: [ { id: "field1", type: "string" }, { id: "field2", type: "number" }, { id: "my_field", type: "email" } ], fieldValues: { field1: "John", field2: "John", my_field: "@" } }
内容的提问来源于stack exchange,提问作者Tamás
相关产品推荐
相关产品推荐

