【发布时间】:2018-03-08 06:35:56
【问题描述】:
假设我有一个带有以下(最新)包的 Typescript 项目:
- q@1.5.0
- typescript@2.5.2
- @types/q@1.0.5
现在假设在我的项目中,我定义了一个返回 Promise 的函数(由 Typescript 的原生环境声明定义):
import * as q from "q";
function doSomethingElseAsync(): Promise<number> {
return q.Promise<number>((resolve, reject) => {
setTimeout(() => resolve(1), 5000);
});
}
编译时,Typescript 报错如下:
error TS2322: Type 'Q.Promise<number>' is not assignable to type 'Promise<number>'.
Types of property 'then' are incompatible.
Type '<U>(onFulfill?: ((value: number) => IWhenable<U>) | undefined, onReject?: ((error: any) => IWhena...' is not assignable to type '<TResult1 = number, TResult2 = never>(onfulfilled?: ((value: number) => TResult1 | PromiseLike<TR...'.
Types of parameters 'onFulfill' and 'onfulfilled' are incompatible.
Type '((value: number) => TResult1 | PromiseLike<TResult1>) | null | undefined' is not assignable to type '((value: number) => IWhenable<TResult1 | TResult2>) | undefined'.
Type 'null' is not assignable to type '((value: number) => IWhenable<TResult1 | TResult2>) | undefined'.
有一段时间,我认为这是因为 Q Promises 与 Typescript 的原生声明不兼容。但是,如果我在函数定义中添加async 关键字,错误就会完全消失。
我对这种行为感到很困惑。这是 Typescript、Q 或 Q 类型中的错误吗?或者这是编译器的一些深奥但预期的行为?
【问题讨论】:
-
可能相关? stackoverflow.com/questions/42689713/… 基本上...... q 承诺不是原生承诺。就像蓝鸟承诺不是原生承诺一样。
-
只要它符合 Typescript 所期望的接口,它是否是原生承诺并不重要。 Q 和 Bluebird 的 promise 在实践中运行良好。
-
对,但更重要的是,它们与界面匹配吗?我不认为他们这样做。
-
啊,我认为你是对的。我将 async 函数的返回类型交换为
q.Promise并得到一个编译器错误,说“它没有引用与 Promise 兼容的构造函数值”。这是有道理的,因为q.Promise不是您使用new调用的构造函数。
标签: typescript promise async-await q