Issue
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?
Solution
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");
Answered By - Titian Cernicova-Dragomir
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.