0

一些库提供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(如果那是实际错误)?
为什么有些库(bluebird、rsvp、ember、...)使用Thenable而不是Promise/ PromiseLike

4

1 回答 1

4

Ajv 的Thenable类型声明表明 的第二个参数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 代码似乎返回了正常的 Promises,因此它不关心类型。所以这对我来说似乎是 AJV 的 TypeScript 声明中的一个错误......我不知道为什么 AJV 不在这里使用 TypeScript 的内置PromiseLike......

于 2018-02-21T21:38:38.360 回答