TypeScript如何基于原接口生成保留属性名、提取instance类型的新类型
TypeScript 泛型实现方案
基础实现(适配你的需求)
直接使用 TypeScript 映射类型即可实现需求,泛型定义如下:
type myBasicType<TType extends Record<string, { instance: unknown }>> = { [Key in keyof TType]: TType[Key]['instance'] }
代码说明
- 泛型约束
TType extends Record<string, { instance: unknown }>用来保证传入的接口所有属性都包含instance字段,提前规避不合法的入参类型 [Key in keyof TType]会遍历原接口的所有属性名,完全保留原属性结构- 每个属性的类型直接映射为原接口对应属性下
instance字段的类型TType[Key]['instance']
完整使用示例
// 示例实例类型定义 type someInstance = { id: number; name: string } type someOtherInstance = { price: number; count: number } // 你的原始接口 interface myType { A: { instance: someInstance, extraProp1: string }, B: { instance: someOtherInstance, extraProp2: boolean } } // 实际使用 const a: myBasicType<myType> = { A: { id: 1, name: '测试' }, // 类型为 someInstance B: { price: 100, count: 10 } // 类型为 someOtherInstance }
通用扩展版本
如果需要适配提取不同的子字段,可以把字段名也作为泛型参数,实现更通用的工具类型:
type ExtractSubField< T extends Record<string, Record<string, unknown>>, SubField extends string > = { [Key in keyof T]: T[Key][SubField] } // 对应你的需求,封装提取instance的类型 type myBasicType<T> = ExtractSubField<T, 'instance'>
内容的提问来源于stack exchange,提问作者Adam Baranyai
相关产品推荐
相关产品推荐

