【问题标题】:Typescript with MongoDB findOne method not working with generic带有 MongoDB findOne 方法的打字稿不适用于泛型
【发布时间】:2021-03-20 03:21:14
【问题描述】:

我正在编写一个类来清理我现有的大量数据库代码。第一步是编写一个类来为我管理Collections,我尝试使用一个具有泛型的类来实现。

interface MongodbItem {
    _id?: ObjectID
}

class CollectionManager<DataType extends MongodbItem> {
    database: Database;
    collection: Collection<DataType>;
    // ...
    async get(id?: ObjectID) {
        if (!id) return await this.collection.find({}).toArray();
        return await this.collection.findOne({ _id: id });
    }
}

然而,尽管将DataType 泛型定义为具有_id,Typescript 给了我以下错误(与.findOne 一致):

Argument of type '{ _id: ObjectID; }' is not assignable to parameter of type 'FilterQuery<DataType>'.
  Type '{ _id: ObjectID; }' is not assignable to type '{ [P in keyof DataType]?: Condition<DataType[P]>; }'

通读手册,似乎以我应该强制它具有_id 属性的方式扩展泛型,所以我不知道为什么仍然会出现此错误。

【问题讨论】:

    标签: mongodb typescript typescript-generics


    【解决方案1】:

    似乎是 a 但带有 Typescript 本身: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/40584 https://github.com/DefinitelyTyped/DefinitelyTyped/issues/39358

    使用解决方法解决

    return this.collection.findOne({ _id: id } as FilterQuery<DataType>);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 2020-10-02
      • 2020-05-26
      • 2021-11-09
      • 2021-10-27
      相关资源
      最近更新 更多