Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript with MongoDB findOne method not working with generic

I am writing a class to clean up a lot of my existing database code. The first step for this was writing a class to manage Collections for me, which I attempted to do using a class with a generic.

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

However, despite defining the DataType generic as having that _id Typescript gives me the following error (On the line with the .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]>; }'

reading through the handbook it looks like extending the generic in the way I am should enforce that it has an _id property, so I do not know why this error is still occuring.

like image 496
Strike Eagle Avatar asked Nov 17 '25 10:11

Strike Eagle


1 Answers

Appears to be a but with Typescript itself: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/40584 https://github.com/DefinitelyTyped/DefinitelyTyped/issues/39358

Solved using workaround

return this.collection.findOne({ _id: id } as FilterQuery<DataType>);
like image 122
Strike Eagle Avatar answered Nov 19 '25 09:11

Strike Eagle