Hongbo Miao Hongbo Miao - 3 months ago 29
TypeScript Question

error TS2348: Value of type 'typeof ObjectID' is not callable. Did you mean to include 'new'?

When I convert a

string
to
ObjectId
, I use

import * as mongoose from 'mongoose';

const objId = mongoose.Types.ObjectId(strId);


It works well in TypeScript 1.x, after updating to TypeScript 2.x, I got the error:


error TS2348: Value of type 'typeof ObjectID' is not callable. Did you
mean to include 'new'?


How can I solve it? Thanks

Answer

The mongoose docs show that you can instantiate ObjectId without the new keyword, but the typescript definitions (at least the ones I've seen, like the one on DefinitelyTyped) don't have that, so if you want to avoid typescript compilation errors you'll need to use the new keyword:

const objId = new mongoose.Types.ObjectId(strId);

You should also be able to do something like:

type ObjectIdConstructor = {
    (str: string): mongoose.Types.ObjectId;
    new (str: string): mongoose.Types.ObjectId;
}

const objId = (mongoose.Types.ObjectId as ObjectIdConstructor)(strId);
Comments