You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 09:52:50