我正在使用Mongoose和Bluebird的打字稿. Mongoose设置为返回Bluebird承诺,但我不知道如何“告诉”TypeScript.
例如,如果我尝试执行以下操作,我有一个Message Mongoose模型:
new Message(messageContent) .save() .then(() => {...}) .catch(next);
TypeScript抱怨在’Promise< void>‘类型中不存在属性’catch’.因为它认为.save()(或任何其他返回Promise的Mongoose方法)返回一个’常规’Promise(实际上没有.catch()方法)而不是Bluebird promise.
如何更改Mongoose方法的返回类型,以便TypeScript知道它返回了Bluebird的承诺?
解决方法
根据DefinitelyTyped的mongoose.d.ts
/** * To assign your own promise library: * * 1. Include this somewhere in your code: * mongoose.Promise = YOUR_PROMISE; * * 2. Include this somewhere in your main .d.ts file: * type MongoosePromise<T> = YOUR_PROMISE<T>; */
因此,您的主.d.ts文件将如下所示:
/// <reference path="globals/bluebird/index.d.ts" /> /// <reference path="globals/mongoose/index.d.ts" /> type MongoosePromise<T> = bluebird.Promise<T>;