2016-12-28 65 views
5

(我已閱讀this post但八月,它並沒有回答我的當前版本打字稿問題。)如何打字稿使用藍鳥2.1+

我目前使用的打字稿1.8在我的項目,這工作得很好:

import * as Promise from "bluebird"; 
async function f() : Promise<void> { 
    return Promise.delay(200); 
} 

但是,如果我試圖用打字稿2.1編譯:

index.ts(2,16): error TS1059: Return expression in async function does not have a valid callable 'then' member. 

谷歌搜索在Typscript使用藍鳥承諾的問題,我也有˚F發現了很多github的討論,評論和PR,但他們都很難理解,並且在討論有趣的觀點時,我無法找到任何說明我現在應該如何運作的地方。

那麼,我該如何在Typescript 2.1中使用Bluebird for Promises?

回答

-3

有關一般性概述,請參閱 SO documentation page 例如,對於藍鳥,你可以只是打字安裝藍鳥。此代碼編譯爲我好:

import Promise = require('bluebird') 
 
Promise.resolve("foo").then(function (msg) { 
 
    console.log(msg) 
 
})

+0

這與我的例子不一樣。我的例子中的錯誤來自於在異步函數中使用Bluebird,這是我非常依賴的。 – Ludwik

+0

另外我認爲你的鏈接已損壞。 – Ludwik

+0

請參閱異步函數中的Bluebird:https://www.npmjs.com/package/babel-plugin-bluebird-async-functions – illeas

0

我在這裏問了同樣的問題:https://github.com/Microsoft/TypeScript/issues/8331

在我自己的答案有工作的結束。以下是如何使用它的打字稿2.3不需要額外的.d.ts文件:

import * as Bluebird from 'bluebird'; 

export interface DummyConstructor extends Bluebird<any> { 
    new<T>(): Bluebird<T>; 
} 

declare global { 
    interface Promise<T> extends Bluebird<T> { 
     then(...args: any[]): any; 
     catch(...args: any[]): any; 
    } 

    interface PromiseConstructor extends DummyConstructor {} 

    var Promise: Promise<any>; 
} 

Promise = Bluebird as any; 

async function test() { 
    console.log('PING'); 
    await Promise.delay(1000); 
    console.log('PONG'); 
} 

test(); 

這是可怕的,針對本地ES7的時候,未來將無法正常工作,因爲在未來async/await根本不會返回藍鳥承諾對此無能爲力。但是,在此之前以及當轉換到ES5時,這將繼續工作。

儘管存在多個any類型,但它似乎有點類型安全。我相信它可以得到改善。