2016-08-24 103 views
2

我正在使用Mongoose和Bluebird打字。 Mongoose設置爲返回Bluebird諾言,但我不知道如何「告訴」TypeScript。屬性'catch'不存在類型'Promise <void>'

舉例來說,我有一個Message貓鼬模型,如果我嘗試做到以下幾點:

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

打字稿抱怨Property 'catch' does not exist on type 'Promise<void>'.,因爲它認爲.save()(或任何其他貓鼬方法返回一個承諾)返回'定期'承諾(其確實沒有.catch()方法),而不是藍鳥承諾。

如何更改Mongoose方法的返回類型,以便TypeScript知道它正在返回藍鳥許諾?

+0

它看起來像是一個用於Mongoose的DefinitelyTyped文件以及Promise [mongoose.d.ts]的擴展(https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/mongoose/mongoose.d.ts )。你有沒有引用這些文件? – Igor

+0

@Igor是的,但是我不想使用Mongoose默認的Promise,我用Bluebird替換了它。 (通過做'mongoose.Promise = require('bluebird')') – Nepoxx

+0

好的,引用[DefinitelyTyped/bluebird/bluebird.d.ts]怎麼樣(https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/ bluebird/bluebird.d.ts)並在'save()'結果上使用強制轉換? – Igor

回答

1

根據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>; 
+2

除了我認爲不應該修改的Typings生成的文件外,我沒有'main''d.ts'文件。我試圖在我定義模型的地方添加該行,但它不起作用。 – Nepoxx

1

我已經結束了這樣延長貓鼬模塊:

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

見我的答案在這裏:Mongoose Promise with bluebird and typescript

+0

當我嘗試這樣做時:'TS2665:模塊擴充不能在頂層範圍中引入新名稱。「我錯過了什麼? – Nepoxx

+0

你在哪裏添加這些行?我創建了一個新的gloabal.d.ts文件並在index.d.ts中引用它。也爲了得到它與最新的貓鼬包的工作,你需要目標es6,看到我的答案在這裏:http://stackoverflow.com/a/39090151/4167200 – Thomas

+0

我不手動管理我的.d.ts文件,我讓Typings採取關心這一點。我在模型文件中內嵌了這些行。 – Nepoxx

相關問題