如何在TypeScript中基于另一接口的键创建自定义类型?
TypeScript中基于现有接口创建依赖键的自定义类型(解决约束错误)
问题核心
你遇到的错误源于泛型参数T extends object的约束过于宽泛,ReturnModelType要求其泛型参数必须满足AnyParamConstructor<any>约束,但原类型未保证T[Key]符合该要求。
正确实现方式
给泛型T添加精确约束,确保它的所有属性类型都适配ReturnModelType的参数要求:
// 导入对应类型(以typegoose库为例,若为自定义类型同理) import { AnyParamConstructor, ReturnModelType } from "@typegoose/typegoose"; // 修正后的映射类型 type TSchemaCollection<T extends Record<string, AnyParamConstructor<any>>> = { [Key in keyof T]: ReturnModelType<T[Key]>; };
使用示例
基于你的IModelCollection接口生成目标类型:
interface IModelCollection { Account: typeof Account; Session: typeof Session; // 其他模型类型... } // 自动生成符合预期的ISchemaCollection类型 type ISchemaCollection = TSchemaCollection<IModelCollection>;
原理说明
- 将
T extends object替换为T extends Record<string, AnyParamConstructor<any>>,明确约束T的所有属性都必须是AnyParamConstructor<any>类型(即ReturnModelType可接受的参数类型)。 - 映射类型
[Key in keyof T]会遍历T的所有键,为每个键生成对应的ReturnModelType<T[Key]>类型,完全匹配你期望的ISchemaCollection结构。
内容的提问来源于stack exchange,提问作者T00rk
相关产品推荐
相关产品推荐

