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

如何定义引用子对象键的TypeScript对象类型?

用TypeScript泛型实现Config的类型关联

你需要让makeReference的参数与form的字段严格绑定,获得类型安全提示,核心是通过泛型把form的结构和txn的函数参数关联起来,具体实现如下:

步骤1:定义泛型Config类型

先明确Form字段的基础类型,再用泛型捕获form的具体结构:

// 定义单个表单字段的类型
type FormField = { type: "string"; pattern: RegExp } | { type: "number" };

// 泛型Config,T代表form的具体结构
type Config<T extends Record<string, FormField>> = {
  txn: {
    // 映射form的字段,生成对应类型的参数(string/number)
    makeReference: (formObj: { 
      [K in keyof T]: T[K]["type"] extends "string" ? string : number 
    }) => string;
  };
  form: T;
};

步骤2:创建带类型安全的Config实例

可以用satisfies关键字让TypeScript自动推导泛型参数,同时保证类型合规:

const config = {
  txn: {
    makeReference: (keys) => `${keys.accountId}_${keys.subjectId}`,
    // 此时keys会自动提示accountId、subjectId、age,且类型分别为string、string、number
    // 写错键名或用错类型会直接报错
  },
  form: {
    accountId: { type: "string", pattern: /\w+/ },
    subjectId: { type: "string", pattern: /\w+/ },
    age: { type: "number" },
  }
} satisfies Config<typeof config.form>;

或者用工厂函数更直观:

function createConfig<T extends Record<string, FormField>>(config: Config<T>) {
  return config;
}

const config = createConfig({
  txn: {
    makeReference: (keys) => `${keys.accountId}_${keys.subjectId}`,
  },
  form: {
    accountId: { type: "string", pattern: /\w+/ },
    subjectId: { type: "string", pattern: /\w+/ },
    age: { type: "number" },
  }
});

为什么这样有效?

  • 泛型T会自动捕获form的具体键和字段类型,不再是模糊的string键
  • 映射类型{[K in keyof T]: ...}根据form字段的type值,生成对应的TypeScript基础类型,实现精准的参数类型提示
  • 无需手动指定泛型参数,TypeScript会自动推导,同时确保txn和form的结构完全匹配

内容的提问来源于stack exchange,提问作者Joey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 23:13:13