TypeScript泛型Repository类使用Pick实现getById类型错误如何解决?
报错原因
代码的核心问题是泛型参数定义不足:当前Repository<T>仅使用了实体类型T一个泛型,primaryKey: keyof T的类型会被推导为T所有键的联合类型,因此Pick<T, typeof this.primaryKey>等价于Pick<T, keyof T>,也就是完整的T类型,自然会要求你传入Seller的全部属性。
解决方案
给抽象仓储类新增第二个泛型参数K extends keyof T,用于限定主键的具体类型:
// 新增泛型K,约束为T的键的子集 export abstract class Repository<T, K extends keyof T> implements IRepository<T> { public entityMap: TableMap<T>; public primaryKey: K; // 主键类型用具体的K而非keyof T constructor(primaryKey: K, entityMap: TableMap<T>) { this.entityMap = entityMap; this.primaryKey = primaryKey; }; // 入参类型改为Pick<T, K> public async getById(id: Pick<T, K>) { const query: Query<T> = new Query<T>(this.entityMap).select().where(id); const entity: T = await query.first(); return entity; }; }
对应修改继承的子类,传入主键的具体字面量类型即可:
// 第二个泛型传入主键的实际类型'id' export class SellerRepository extends Repository<Seller, 'id'> { constructor() { const primaryKey: keyof Seller = `id`; const sellerMap: SellerMap = new SellerMap(); super(primaryKey, sellerMap); }; }
修改后原有调用代码可以正常运行,不会再要求传入额外属性。
内容的提问来源于stack exchange,提问作者Rodrigo Ferretti
相关产品推荐
相关产品推荐

