【发布时间】: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