属性 'catch' 在类型 'Promise<void>' 上不存在
Property 'catch' does not exist on type 'Promise<void>'
我在打字稿中使用 Mongoose 和 Bluebird。 Mongoose 设置为 return Bluebird promises,但我不知道如何 "tell" TypeScript 关于它。
例如,我有一个 Message
Mongoose 模型,如果我尝试执行以下操作:
new Message(messageContent)
.save()
.then(() => {...})
.catch(next);
TypeScript 抱怨 Property 'catch' does not exist on type 'Promise<void>'.
因为它认为 .save()
(或任何其他 Mongoose 方法 return 一个 Promise)return 是一个 'regular' Promise(它确实没有 .catch()
方法)而不是 Bluebird 承诺。
如何更改 return 类型的 Mongoose 方法,以便 TypeScript 知道它是 returning Bluebird promise?
根据 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>;
我最终完成了扩展 mongoose 模块的工作:
declare module "mongoose" {
import Bluebird = require("bluebird");
type MongoosePromise<T> = Bluebird<T>;
}
在这里查看我的回答:
我在打字稿中使用 Mongoose 和 Bluebird。 Mongoose 设置为 return Bluebird promises,但我不知道如何 "tell" TypeScript 关于它。
例如,我有一个 Message
Mongoose 模型,如果我尝试执行以下操作:
new Message(messageContent)
.save()
.then(() => {...})
.catch(next);
TypeScript 抱怨 Property 'catch' does not exist on type 'Promise<void>'.
因为它认为 .save()
(或任何其他 Mongoose 方法 return 一个 Promise)return 是一个 'regular' Promise(它确实没有 .catch()
方法)而不是 Bluebird 承诺。
如何更改 return 类型的 Mongoose 方法,以便 TypeScript 知道它是 returning Bluebird promise?
根据 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>;
我最终完成了扩展 mongoose 模块的工作:
declare module "mongoose" {
import Bluebird = require("bluebird");
type MongoosePromise<T> = Bluebird<T>;
}
在这里查看我的回答: