TypeScript Override for ES6 Promise with Bluebird

I have a Node.js library that uses promises with TypeScript declarations using ES6 Promise, although the library itself can be configured to use any promise library.

So, I have no problem transferring Bluebirdto this library so that it can use it.

The problem is how to make the Bluebird promise interface visible at the declarative level, since my library only declares its interface through ES6 Promise.

Is there a way to make the compiler realize that I am using a different Promise protocol without modifying the library itself?

The latter, of course, is a trick, as there would be no question if I could just change the library.

And if this helps to understand what this library is, open this simple interface:

interface Protocol {
    methodName(param1:string, param2:number):Promise<Object[]>
}

and then multiply its size 1000 times.

So, I can’t just fake the protocol with my own file. I need to figure out how to tell the compiler that Promiseit is not ES6 by default, but one that provides Bluebird TypeScript.

+4
source share
1 answer

You could overwrite the Promise type with the union https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types

This is an unacceptable way.

import Bluebird from 'bluebird';

type Promise = Promise | Bluebird;

Taking @Paarth's comment above, you can come up with your Bluebird promise for ES6 promise.

This is the preferred way.

:

interface Protocol {
    methodName(param1:string, param2:number):Promise<Object[]>
}

:

import Bluebird from 'bluebird';

class Http implements Protocol {
  methodName(url: string, payload: number): Promise<Object[]> {
    return <Promise<Object[]>>new Bluebird((resolve, reject) => {

      // Do whatever you need to do ... use the url & payload

      resolve([{ data: 'Done' }]);
    });
  }
}


let http = new Http();

http.methodName('//get-some-data', 10);

: , - , jsbin Typescript

0

All Articles