简体   繁体   English

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

[英]Typescript Generic Repository Pattern - Return Type with Methods

When trying to create a generic repository, I ended up with an implementation that looks like this: 当尝试创建通用存储库时,我最终获得了一个类似于以下内容的实现:

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

And I use it like this, Which is less than ideal as I need to pass the class name in addition to specifying the generic type: 我这样使用它,这不理想,因为除了指定泛型类型之外,我还需要传递类名:

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

Is there a solution that is cleaner on one hand, and would still allow me to return the correct type? 是否有一方面更清洁的解决方案,并且仍然可以让我返回正确的类型?

There is no way to create new class instances based on generic type. 无法基于泛型创建新的类实例。 Because there is no any typing information in the compiled version of your code in JavaScript, so you can't use T to create a new object. 由于JavaScript的代码编译版本中没有任何键入信息,因此您不能使用T创建新对象。

You can do this in a non-generic way by passing the type into the constructor - this is what exactly you're doing in your example. 您可以通过将类型传递给构造函数来以非泛型方式进行此操作-这正是您在示例中所做的。

For more details - follow this post . 有关更多详细信息,请关注此帖子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM