首页 > 解决方案 > 类型在其自己的“then”方法的实现回调中被直接或间接引用

问题描述

使用 Google Auth2 API 的类型时会出现错误 - @types/gapi.auth21062如果我创建一个使用该gapi.auth2.GoogleAuth类型解析的 Promise,编译器会抛出一个错误。

Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method.

打字有这个小怪癖:

class GoogleAuth {
    ...
    /**
     * Calls the onInit function when the GoogleAuth object is fully initialized, or calls the onFailure function if
     * initialization fails.
     */
    then(onInit: (googleAuth: GoogleAuth) => any, onFailure?: (reason: {error: string, details: string}) => any): any;
    ...
}

使用的代码是这样的:

async function getGapi() {
    return new Promise<gapi.auth2.GoogleAuth>(resolve => {
        ...
    });
}

承诺范围内的任何内容都无关紧要,只要它具有那种GoogleAuth类型 - 它就会感到不安。

问题肯定与类型有关,创建包装器或完全忽略错误可能很容易。GoogleAuth 对象是“thennable”,但为什么会导致任何问题?有循环引用之类的吗?

更令人不安的是1062错误很少。我还没有求助于阅读编译器代码,但到目前为止我无法弄清楚它试图告诉我什么。

标签: typescript

解决方案


编辑:回答我自己的问题。

谷歌的文档明确说明了这一点:

警告:不要调用Promise.resolve()和类似的结果 gapi.auth2.init()。由于返回的 GoogleAuth 对象实现了then() 自行解析的方法,因此它将创建无限递归。

这意味着无论我们使用 Typescript 还是纯 Javascript 都会有问题。

因此,Typescript 在这里保护用户免受无限递归。这是否是它的意图,我不知道。措辞似乎表明它的问题完全是编译器的打字问题或限制。但它实际上在做一项重要的工作。

TL;DR:promise 结果是另一个返回自身的promise。编译器错误是防止无限递归。


推荐阅读