类型在其自己的“ then”方法的实现回调中直接或间接引用

gwi*_*llz 6 typescript

使用Google Auth2 API键入错误时会出错@types/gapi.auth21062如果我创建一个使用gapi.auth2.GoogleAuth类型解析的承诺,则编译器将引发错误。

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;
    ...
}
Run Code Online (Sandbox Code Playgroud)

使用的代码是这样的:

async function getGapi() {
    return new Promise<gapi.auth2.GoogleAuth>(resolve => {
        ...
    });
}
Run Code Online (Sandbox Code Playgroud)

只要有这种GoogleAuth类型,promise范围内的任何内容都没有关系-这很不高兴。

问题肯定与类型有关,创建包装器或完全忽略错误可能很容易。GoogleAuth对象是“可扩展的”,但是为什么会引起任何问题呢?有圆形参考书吗?

更令人困扰的是1062错误很少。我尚未求助于阅读编译器代码,但到目前为止,我仍无法弄清它试图告诉我什么。

gwi*_*llz 6

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

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

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

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

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

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