Filter _id type appears to be inferred incorrectly for generic types

Creating an object of type Filter, the type of ID inferred appears to be incorrect when using generic types.
The example below will reproduce the error I am seeing:

node-mongodb-native v4.2.2

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

type AppDocument = Document & { id: string }
type DbDocument<T extends AppDocument> = Omit<T, 'id'> & {
  _id: T['id']
}

export function set<T extends AppDocument>(): void {
  // fails type checking
  const query1: Filter<DbDocument<T>> = { _id: 'a-custom-id' }
  // passes type checking
  const query2: Filter<DbDocument<T>> = {
    _id: new ObjectId()
  }
}

type SimpleDocument = Document & { _id: string }

export function other(): void {
  // passes type checking
  const query: Filter<SimpleDocument> = { _id: 'a-custom-id' }
}

EDIT: ID should be ObjectId

1 Like