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

TypeScript中如何根据对象兄弟字段值类型化字段?

如何根据对象的兄弟字段值类型化对象字段

要实现指定name字段为T的某个属性时,自动推导layout字段为对应的Layout<T[K]>类型,你需要让name和layout的类型建立关联绑定,而非使用泛型默认值导致的松散联合类型。

问题根源

原代码中AutoCellProps<T>的泛型参数F默认值为keyof T,这会让cells数组中的每个元素成为所有可能AutoArrayProps的联合类型,TypeScript无法将name的具体值与layout的类型关联起来。

解决方案

通过映射类型生成绑定类型的联合,让每个cell的name和layout类型一一对应:

export interface Layout<T> {
  cells: (Layout<T> | AutoCellUnion<T>)[];
}

// 针对单个字段K的数组单元格类型
export interface AutoArrayProps<T, K extends keyof T> {
  dataType: 'Array';
  name: K;
  layout: Layout<T[K]>;
}

// 生成所有字段对应的数组单元格类型的联合
type AutoCellUnion<T> = { [K in keyof T]: AutoArrayProps<T, K> }[keyof T];

type formData = {
  section1: { field1: string },
  section2: { field2: string },
}

const layout: Layout<formData> = {
  cells: [
    {
      dataType: 'Array',
      name: 'section1',
      // 此处自动推导为 Layout<{ field1: string }>
      layout: {
        cells: []
      }
    },
    {
      dataType: 'Array',
      name: 'section2',
      // 此处自动推导为 Layout<{ field2: string }>
      layout: {
        cells: []
      }
    }
  ]
}

原理说明

  • AutoCellUnion<T>通过映射类型遍历T的所有键K,为每个键生成对应的AutoArrayProps<T, K>类型,最后通过[keyof T]取出所有值的联合类型。
  • 此时cells数组中的每个元素要么是嵌套的Layout<T>,要么是某个具体K对应的AutoArrayProps,TypeScript会根据name字段的具体值,自动锁定对应的layout类型。

内容的提问来源于stack exchange,提问作者Naseeruddin V N

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:33:16