错误 TS2348:'typeof ObjectID' 类型的值不可调用。您是要包括 'new' 吗?

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

当我将 string 转换为 ObjectId 时,我使用

import * as mongoose from 'mongoose';

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

它在 TypeScript 1.x 中运行良好,更新到 TypeScript 2.x 后,出现错误:

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

我该如何解决?谢谢

猫鼬文档显示您可以在没有 new 关键字的情况下实例化 ObjectId,但是打字稿定义(至少我见过的定义,如 the one on DefinitelyTyped)不会没有那个,所以如果你想避免打字稿编译错误,你需要使用 new 关键字:

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

您还应该能够执行以下操作:

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

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