Typescript通用存储库模式-返回类型和方法

Typescript通用存储库模式-返回类型和方法,typescript,Typescript,在尝试创建通用存储库时,我最终得到了如下实现: export class DynamoDbRepository<T extends IRepositoryItem> extends BaseRepository<T> { private _tableName: string = void 0; private _type; constructor(tableName: string, type: new () => T) { ...

在尝试创建通用存储库时,我最终得到了如下实现:

export class DynamoDbRepository<T extends IRepositoryItem> extends BaseRepository<T> {
    private _tableName: string = void 0;
    private _type;

    constructor(tableName: string, type: new () => T) {
    ...
    }

    ...

    findOne(appId: string, id: string): Promise<T> {
      const params = {
        Key: {
            "Id": id,
            "AppId": appId 
        },
        TableName: this._tableName
      }

      return new Promise((resolve, reject) => {
        DynamoDbClient.get(params, (error, result) => {
            // handle potential errors
            if (error) {
                Logger.error(error);
                reject(new Error(`GetItemFailed for table '${this._tableName}'`));
            }

            // no items found
            if (!result.Item) reject(new Error(`ItemNotFound in table '${this._tableName}'`));

            // create instance of correct type, map properties
            let item = new this._type();
            Object.keys(result.Item).forEach((key) => {
                item[key] = result.Item[key];
            })

            // return the item
            resolve(item);
        });
    });
}
导出类DynamoDbRepository扩展BaseRepository{
private _tableName:string=void 0;
私有型;
构造函数(tableName:string,type:new()=>T){
...
}
...
findOne(appId:string,id:string):承诺{
常量参数={
关键:{
“Id”:Id,
“AppId”:AppId
},
TableName:this.\u TableName
}
返回新承诺((解决、拒绝)=>{
DynamoDbClient.get(参数,(错误,结果)=>{
//处理潜在的错误
如果(错误){
记录器错误(error);
拒绝(新错误(`GetItemFailed for table'${this.\u tableName}`');
}
//没有找到任何项目
如果(!result.Item)拒绝(新错误(`ItemNotFound in table'${this.\u tableName}`));
//创建正确类型的实例,映射属性
让item=newthis._type();
Object.key(result.Item).forEach((key)=>{
项目[关键]=结果。项目[关键];
})
//退货
解决(项目);
});
});
}
我这样使用它,这不太理想,因为除了指定泛型类型之外,我还需要传递类名:

const userRepository = new DynamoDbRepository<User>(Tables.USERS_TABLE, User);
constuserrepository=newdynamodbrepository(Tables.USERS\u TABLE,User);

有没有一种解决方案一方面更干净,而且仍然允许我返回正确的类型?

没有办法基于泛型类型创建新的类实例。因为JavaScript中代码的编译版本中没有任何类型信息,所以不能使用
t
创建新对象

通过将类型传递到构造函数中,您可以以非泛型的方式实现这一点——这正是您在示例中所做的


有关更多详细信息,请遵循此说明。

我非常确定您正确编写了
DynamoDbRepository
类,您可以只编写:
const userRepository=new DynamoDbRepository(Tables.USERS\u TABLE,User)
。变量
userRepository
仍将获得类型
DynamoDbRepository
。这不是您的目标吗?足够接近:)将很酷地看到未来版本的Typescript能够在幕后处理此问题。