Lud*_*wik 9 javascript promise typescript bluebird typescript2.1
(我已经阅读了这篇文章,但它是从八月开始的,并没有回答我当前打字稿版本的问题.)
我目前在我的项目中使用Typescript 1.8,这很好用:
import * as Promise from "bluebird";
async function f() : Promise<void> {
return Promise.delay(200);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试使用Typescript 2.1进行编译:
index.ts(2,16): error TS1059: Return expression in async function does not have a valid callable 'then' member.
Run Code Online (Sandbox Code Playgroud)
谷歌搜索在Typscript中使用Bluebird Promises的问题,我也发现了许多github讨论,评论和PR,但它们都很难掌握,在讨论有趣的观点时,我找不到任何说我应该怎么做的让它现在起作用.
那么,我怎么能在Typescript 2.1中使用Bluebird for Promises呢?
小智 6
考虑@types/bluebird-global如下使用。
npm install --save-dev @types/bluebird-global
Run Code Online (Sandbox Code Playgroud)
在您的主要入口点中将其导入一次。
// The same Promise API, everywhere.
import * as Promise from 'bluebird'
global.Promise = Promise
Run Code Online (Sandbox Code Playgroud)
有关更多上下文,请参见DefinitelyTyped问题#11027。
我在这里问了同样的问题:https ://github.com/Microsoft/TypeScript/issues/8331
最终我自己的答案奏效了。以下是如何在 TypeScript 2.3 中使用它而无需额外.d.ts文件:
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();
Run Code Online (Sandbox Code Playgroud)
这太可怕了,将来在针对原生 ES7 时将无法工作,因为将来async/await根本不会返回 Bluebird 承诺,对此我们无能为力。然而,在那之前以及转换为 ES5 时,这将继续有效。
尽管有多种any类型,但它似乎有些类型安全。我确信它可以改进。
| 归档时间: |
|
| 查看次数: |
7739 次 |
| 最近记录: |