【问题标题】:Property 'catch' does not exist on type 'Promise<void>'类型“Promise<void>”上不存在属性“catch”
【发布时间】:2016-12-31 20:22:29
【问题描述】:

我正在使用 Mongoose 和 Bluebird 和 typescript。 Mongoose 设置为返回 Bluebird 承诺,但我不知道如何“告诉”TypeScript。

例如,如果我尝试执行以下操作,我有一个 Message Mongoose 模型:

new Message(messageContent)
  .save()
  .then(() => {...})
  .catch(next);

TypeScript 抱怨 Property 'catch' does not exist on type 'Promise&lt;void&gt;'. 因为它认为 .save()(或任何其他返回 Promise 的 Mongoose 方法)返回一个“常规”Promise(它确实没有 .catch() 方法)而不是 Bluebird 承诺.

如何更改 Mongoose 方法的返回类型,以便 TypeScript 知道它正在返回 Bluebird 承诺?

【问题讨论】:

  • 看起来有一个Mongoose的DefinitelyTyped文件以及它的Promise扩展名mongoose.d.ts。您是否引用了这些文件?
  • @Igor 是的,但是我不想使用 Mongoose 默认拥有的 Promise,我将其替换为 Bluebird。 (通过mongoose.Promise = require('bluebird')
  • 好的,那么引用DefinitelyTyped/bluebird/bluebird.d.ts 并在save() 结果上使用强制转换呢?
  • 即使是“常规”承诺也有一个catch 方法。只有 Mongoose 的承诺没有。

标签: node.js typescript mongoose promise bluebird


【解决方案1】:

我最终扩展了 mongoose 模块:

declare module "mongoose" {
    import Bluebird = require("bluebird");
    type MongoosePromise<T> = Bluebird<T>;
}

在这里查看我的答案:Mongoose Promise with bluebird and typescript

【讨论】:

  • 当我尝试得到:TS2665:Module augmentation cannot introduce new names in the top level scope. 我错过了什么?
  • 你在哪里添加了这些行?我创建了一个新的 gloabal.d.ts 文件并在 index.d.ts 中引用它。还要让它与你需要以 es6 为目标的最新 mongoose 包一起工作,请在此处查看我的答案:stackoverflow.com/a/39090151/4167200
  • 我不手动管理我的 .d.ts 文件,我让 Typings 来处理。我在模型文件中添加了这些行。
【解决方案2】:

根据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>;

【讨论】:

  • 我没有“主”d.ts 文件,除了我认为不应修改的 Typings 生成的文件。我尝试在我定义模型的位置添加该行,但它不起作用。
猜你喜欢
  • 2018-07-17
  • 2019-02-04
  • 2023-03-08
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
相关资源
最近更新 更多