How to use Bluebird in Typescript 2.1+

(I read this post , but this is from August, and it does not answer my question for the current version of typescript.)

I am currently using typescript 1.8 in my project and this works fine:

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

But if I try to compile with typescript 2.1:

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

Turning to the issue of using Bluebird Promises in Typscript, I also found a lot of discussions, comments, and PR, but they are very difficult to understand, and discussing interesting points, I can not find anywhere where it says how I should get it to work now.

So how can I use Bluebird for Promises in typescript 2.1?

+5
source share
3 answers

I asked the same question: https://github.com/Microsoft/TypeScript/issues/8331

In the end, my own answer worked there. Here's how to use it in TypeScript 2.3 without the extra .d.ts file:

 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(); 

This is terrible and will not work in the future when setting up your own ES7, because in the future, async / await simply will not return Bluebird promises, and nothing can be done about it. However, until then, when transferring to ES5, this will continue to work.

Despite several types of any , it seems somewhat type safe. I am sure this can be improved.

0
source

Consider using @types/bluebird-global as follows.

 npm install --save-dev @types/bluebird-global 

Import it once into your main entry point.

 // The same Promise API, everywhere. import * as Promise from 'bluebird' global.Promise = Promise 

See Definitely a problem with type # 11027 for further context.

0
source

For a general overview, take a look at the SO documentation page for example. for bluebird, you can only typify the installation of bluebird. This code is great for me:

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

Source: https://habr.com/ru/post/1261979/


All Articles