Why isn't my MongoDB ObjectID recognised as a type in TypeScript?

  1. yarn add @types/mongodb
  2. use import import {ObjectID} from 'mongodb';

That's enough to use ObjectID as type nowadays.


Even with types installed typescript will not correctly type require("mongodb").ObjectId. You need to use require as part of an import :

import mongodb = require("mongodb");
const ObjectID = mongodb.ObjectID;
const id: mongodb.ObjectID = new ObjectID("5b681f5b61020f2d8ad4768d");

If you want to stick to your original version, you have to realize you are not importing the type, you are just importing the constructor. Sometimes types and values have the same name and are imported together giving the illusion that are the same thing, but really types and values live in different universes. You can declare the associated type and get it from the module type:

const ObjectID = require("mongodb").ObjectID;
type ObjectID= typeof import("mongodb").ObjectID;
const id: ObjectID = new ObjectID("5b681f5b61020f2d8ad4768d");