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

如何在TypeScript中动态获取接口所有属性类型并合并为单个类型

动态获取TypeScript接口所有属性类型的联合类型

你可以通过索引类型查询的方式动态生成接口所有属性类型的联合类型,无需手动枚举每个字段:

// 自动生成ProductForm所有属性类型的联合类型
type FormValueTypes = ProductForm[keyof ProductForm];

原理说明

  • keyof ProductForm 会返回接口所有键名的联合类型:'name' | 'id' | 'categoryId' | 'status'
  • 用这个键名联合类型去索引ProductForm,即ProductForm[keyof ProductForm],会自动映射出每个键对应的属性类型,最终得到所有类型的联合:string | number | ProductStatus

这样当ProductForm新增或修改字段时,FormValueTypes会自动同步更新,不需要手动维护。

进阶优化:让字段名与值类型严格绑定

如果希望函数的字段名和对应值的类型严格匹配(避免传入字段名和值类型不匹配的情况),可以用泛型进一步约束:

const updateProductFormField = <K extends keyof ProductForm>(name: K, value: ProductForm[K]) => {
  // 更新逻辑示例
  console.log(`更新字段${name}为:`, value);
};

// 使用示例:类型检查会自动生效
updateProductFormField('name', '新商品'); // 正确,value是string
updateProductFormField('id', 123); // 正确,value是number
updateProductFormField('status', ProductStatus.ACTIVE); // 正确,value是枚举值
updateProductFormField('categoryId', 'abc'); // 报错,categoryId要求number类型

这种方式比单纯使用联合类型更安全,能在编译期就拦截类型不匹配的错误。

内容的提问来源于stack exchange,提问作者Wai Yan Hein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:46:08