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

时间:2018-08-26 15:43:50

标签: typescript

当尝试创建通用存储库时,我最终得到了一个类似于以下内容的实现:

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);
        });
    });
}

我这样使用它,这不理想,因为除了指定泛型类型之外,我还需要传递类名:

const userRepository = new DynamoDbRepository<User>(Tables.USERS_TABLE, User);

有没有一种更清洁的解决方案,并且仍然可以让我返回正确的类型?

1 个答案:

答案 0 :(得分:0)

无法基于泛型类型创建新的类实例。由于JavaScript的代码编译版本中没有任何键入信息,因此您无法使用T创建新对象。

您可以通过将类型传递给构造函数以非通用的方式进行操作-这正是您在示例中所做的。

有关更多详细信息,请遵循此post

相关问题