如何基于对象属性类型自动生成泛型更新类型?
TypeScript 批量生成带IUpdate包装的对象类型
你可以使用TypeScript映射类型来实现这个需求,无需逐个显式定义属性。
首先回顾你已有的接口定义:
interface ICustomer { name: string; age: number; tags: string[]; } interface IUpdate<T> { changed: boolean; value: T; }
之前尝试的Record类型无法满足需求,因为它会将所有属性设置为统一的IUpdate类型,而我们需要每个属性对应原ICustomer中属性的具体类型进行包装。
正确的类型定义写法如下:
type CustomerUpdate = { [K in keyof ICustomer]: IUpdate<ICustomer[K]>; };
说明
这个映射类型会遍历ICustomer的所有键K,对每个键对应的原类型ICustomer[K],用IUpdate进行包装,最终生成的CustomerUpdate类型和你手动定义的ICustomerUpdate完全等价:
name属性类型为IUpdate<string>age属性类型为IUpdate<number>tags属性类型为IUpdate<string[]>
你可以直接使用这个类型,比如:
const customerUpdate: CustomerUpdate = { name: { changed: true, value: "张三" }, age: { changed: false, value: 28 }, tags: { changed: true, value: ["会员", "活跃用户"] } };
内容的提问来源于stack exchange,提问作者armageddon
相关产品推荐
相关产品推荐

