ES6 Promise / Typescript and the Bluebird Promise

感情迁移 提交于 2019-12-05 00:08:16

I was dealing with

TS2322: Type 'Bluebird' is not assignable to type 'Promise'. Property '[Symbol.toStringTag]' is missing in type 'Bluebird'.

and found this thread: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/10801

The TL;DR; version of it is to do one of the following:

  1. In each of your .ts entry files add the following to overwrite the global promise:

    import * as Bluebird from 'bluebird';

    declare global { export interface Promise<T> extends Bluebird<T> {} }

Or

  1. wrap all promises in a Bluebird promise constructor. There is some runtime overhead here and it is listed as an anti pattern on Bluebird's site.

As an aside, I could not get the second option to work, but the first worked fine for me.

Since there is no [Symbol.toStringTag] in Bluebird, it's incompatible indeed. There are other things that differ Bluebird implementation from native Promise - scheduler, error handling... The correct way to handle this is:

const promise: Promise<type> = Promise.resolve<type>(bluebirdPromise);

If runtime compatibility is not an issue for sure, this can be addressed with type casting only in relatively type-safe manner:

const promise: Promise<type> = <Promise<type>><any><Bluebird<type>>bluebirdPromise;

or

const promise: Promise<type> = <Promise<type>><PromiseLike<type>>bluebirdPromise;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!