TypeScript errors in DataSource class for filter and return types

Hello, I’m trying to create a DataSource class (for use in GraphQL resolvers) where I’m running into some TypeScript errors and I can’t figure out how to solve them. Hoping someone here has the solution :blush:

A minimum version of the DataSource to reproduce both errors:

import type { Collection, Document, ObjectId } from 'mongodb'

class DataSource<TSchema extends Document> {
  collection: Collection<TSchema>

  async find(ids: ObjectId[]) {
    const docs = await this.collection.find({ _id: { $in: ids } }).toArray()
    const docsById: { [id: string]: TSchema } = {}

    docs.forEach(doc => {
      docsById[doc._id.toString()] = doc
    })

    return ids.map(id => docsById[id.toString()] ?? null)
  }
}

The first error is in the find filter:

Argument of type '{ _id: { $in: ObjectId[]; }; }' is not assignable to parameter of type 'Filter<TSchema>'.

Pretty sure the filter is valid since the code is working how I expect it to work, so why is TypeScript raising an error here?

The second error is in the assignment to docsById:

Type 'WithId<TSchema>' is not assignable to type 'TSchema'. 'WithId<TSchema>' is assignable to the constraint of type 'TSchema', but 'TSchema' could be instantiated with a different subtype of constraint 'Document'.

What I left out in this minimum version is that I actually extends from a subclass of Document which included _id: ObjectId among other default fields, but that doesn’t change the error.

I can make it work by using WithId<TSchema> as type for values of docsById but I want to know why I’m getting this error even though the exact same TSchema is used in Collection<TSchema> as well as type for values of docsById. It shouldn’t be possible to get a different subtype here.

Thanks in advance for any help!