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

Viewed 14544

I'm using Node.js with MongoDB and TypeScript.

The following two lines of code:

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

compile without error.

But when I change the second line to:

const id: ObjectID = new ObjectID("5b681f5b61020f2d8ad4768d");

I get an error:

Cannot find name 'ObjectID'

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

3 Answers

UPDATE:

mongodb provides its own types. @types/mongodb is no longer needed.

OLD ANSWER:

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

For new versions, do this instead:

import { ObjectId } from 'bson';

Related