ES6 Promise / Typescript and the Bluebird Promise
我有一个nodejs / typescript 2项目,并使用es6-promise软件包。
现在我想摆脱多余的包,因为我可以直接在打字稿中定位ES6。
所以我删除了es6-promise包,并将tsconfig.json更改为目标es6。
1 2 3 4 5 6 | { "compilerOptions": { "target":"es6", // ... } } |
许多第三方软件包使用Bluebird Promise,但是Promise定义与github上不同文章中所述的默认es6 Promise不兼容。
- bluebird 3.0定义不可分配给ES6 Promises
- 提供一种在es6编译目标中全局加载Bluebird的方法。
- 将Symbol.toStringTag添加到Promise实例
所以我收到以下错误。
TS2322: Type 'Bluebird' is not assignable to type 'Promise'. Property '[Symbol.toStringTag]' is missing in type 'Bluebird'.
npm @ types / bluebird-global上还有其他类型的软件包。
在一篇博客文章中,用户建议使用它而不是@ types / bluebird,但是一些第三方软件包(例如sequelize键入)引用了bluebird而不是bluebird-global,因此我因缺少bluebird的类型而遇到另一个错误。
有什么好的方法可以使其正常工作?
我当时正在处理
TS2322: Type 'Bluebird' is not assignable to type 'Promise'. Property '[Symbol.toStringTag]' is missing in type 'Bluebird'.
并发现此线程:
https://github.com/DefinitelyTyped/DefinitelyTyped/issues/10801
TL; DR;版本是执行以下操作之一:
在每个.ts条目文件中,添加以下内容以覆盖全局承诺:
要么
顺便说一句,我没有第二种选择可以工作,但是第一种选择对我来说很好。
由于Bluebird中没有
1 | const promise: Promise<type> = Promise.resolve<type>(bluebirdPromise); |
如果不确定运行时兼容性不是问题,则只能以相对类型安全的方式使用类型转换解决此问题:
1 | const promise: Promise<type> = <Promise<type>><Bluebird<type>>bluebirdPromise; |
要么
1 | const promise: Promise<type> = <Promise<type>><PromiseLike<type>>bluebirdPromise; |