How to use Bluebird in Typescript 2.1+

13,242

Solution 1

Consider using @types/bluebird-global as follows.

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

Import this once in your main entrypoint.

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

See DefinitelyTyped issue #11027 for further context.

Solution 2

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

In the end my own answer there worked. Here's how to use it in TypeScript 2.3 without an 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();

It's horrible and won't work in the future when targeting native ES7, because in the future async / await simply won't return Bluebird promises and nothing can be done about that. However, until then and when transpiling to ES5 this will keep working.

In spite of the multiple any types, it seems somewhat type-safe. I'm sure it could be improved.

Share:
13,242
Ludwik
Author by

Ludwik

self-taught amateur programmer; Currently making games in Java in my spare time, but have basic knowledge of javascript and html5.

Updated on June 07, 2022

Comments

  • Ludwik
    Ludwik about 2 years

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

    I'm 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.
    

    Googling the issue of using Bluebird Promises in Typscript, I have also found many github discussions, comments and PRs, but they are all very hard to grasp and while discussing interesting points, I can't find anywhere that says how I'm supposed to get this to work now.

    So, how am I supposed to be able to use Bluebird for Promises in Typescript 2.1?