一些库提供Thenable
接口类型 fe AJV。
关于他们,我有些不明白。鉴于这个最小的代码
const foo: Ajv.Thenable<boolean> = new Promise<boolean>((resolve, reject) => {
if ("condition")
resolve(true)
reject("Nope")
})
TypeScript 编译器抛出一个我无法理解的错误。
error TS2322: Type 'Promise<boolean>' is not assignable to type 'Thenable<boolean>'.
Types of property 'then' are incompatible.
Type '<TResult1 = boolean, TResult2 = never>(onfulfilled?: ((value: boolean) => TResult1 | PromiseLike<...' is not assignable to type '<U>(onFulfilled?: ((value: boolean) => U | Thenable<U>) | undefined, onRejected?: ((error: any) =...'.
Types of parameters 'onfulfilled' and 'onFulfilled' are incompatible.
Type '((value: boolean) => U | Thenable<U>) | undefined' is not assignable to type '((value: boolean) => U | PromiseLike<U>) | null | undefined'.
Type '(value: boolean) => U | Thenable<U>' is not assignable to type '((value: boolean) => U | PromiseLike<U>) | null | undefined'.
Type '(value: boolean) => U | Thenable<U>' is not assignable to type '(value: boolean) => U | PromiseLike<U>'.
Type 'U | Thenable<U>' is not assignable to type 'U | PromiseLike<U>'.
Type 'Thenable<U>' is not assignable to type 'U | PromiseLike<U>'.
Type 'Thenable<U>' is not assignable to type 'PromiseLike<U>'.
Types of property 'then' are incompatible.
Type '<U>(onFulfilled?: ((value: U) => U | Thenable<U>) | undefined, onRejected?: ((error: any) => U | ...' is not assignable to type '<TResult1 = U, TResult2 = never>(onfulfilled?: ((value: U) => TResult1 | PromiseLike<TResult1>) |...'.
Types of parameters 'onFulfilled' and 'onfulfilled' are incompatible.
Type '((value: U) => TResult1 | PromiseLike<TResult1>) | null | undefined' is not assignable to type '((value: U) => TResult2 | Thenable<TResult2>) | undefined'.
Type 'null' is not assignable to type '((value: U) => TResult2 | Thenable<TResult2>) | undefined'.
编译器究竟在哪里认为TypeScripts ES6 Promise会返回null
(如果那是实际错误)?
为什么做一些图书馆(蓝鸟,RSVP,烬,...)的使用Thenable
,而不是Promise
/ PromiseLike
?
Ajv 的Thenable
类型声明表示 to 的第二个参数then
(通常称为onRejected
)在调用时必须返回与<U>
第一个onFulfilled
参数相同的类型。ES6 承诺,以及 TypeScript 的Promise
/ PromiseLike
,没有这样的限制。
例如,在这段代码中:
const p1: PromiseLike<boolean> = /* ... */
const p2 = p1.then(() => true, () => 123)
TypeScript 将(正确)推断 p2 具有 type PromiseLike<number | boolean>
。使用 Ajv 的Thenable
类型声明,等效代码将无法编译,因为 123 不可分配给布尔值。
实际的 AJV JavaScript 代码似乎返回正常的 Promise,因此它不关心类型。所以这对我来说似乎是 AJV 的 TypeScript 声明中的一个错误......我不知道为什么 AJV 没有在PromiseLike
这里使用内置的 TypeScript ......
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句