How to use Bluebird in Typescript 2.1+
Asked Answered
B

2

13

(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?

Buskin answered 28/12, 2016 at 9:59 Comment(0)
B
8

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.

Brookins answered 21/3, 2018 at 6:12 Comment(0)
A
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.

Amorphous answered 10/5, 2017 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.