node.js – ‘Promise’类型中不存在属性’catch’

我正在使用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>;

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...