typescript - 类型在其自己的“then”方法的实现回调中被直接或间接引用
问题描述
使用 Google Auth2 API 的类型时会出现错误 - @types/gapi.auth2
。1062
如果我创建一个使用该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错误很少。我还没有求助于阅读编译器代码,但到目前为止我无法弄清楚它试图告诉我什么。
解决方案
编辑:回答我自己的问题。
谷歌的文档明确说明了这一点:
警告:不要调用
Promise.resolve()
和类似的结果gapi.auth2.init()
。由于返回的 GoogleAuth 对象实现了then()
自行解析的方法,因此它将创建无限递归。
这意味着无论我们使用 Typescript 还是纯 Javascript 都会有问题。
因此,Typescript 在这里保护用户免受无限递归。这是否是它的意图,我不知道。措辞似乎表明它的问题完全是编译器的打字问题或限制。但它实际上在做一项重要的工作。
TL;DR:promise 结果是另一个返回自身的promise。编译器错误是防止无限递归。
推荐阅读
- javascript - 循环槽数组渲染jsx元素
- reactjs - FullCalender v5.0 不支持 React 的 viewRender
- javascript - 运行 ALTER 枚举时出现 SQL 错误将 VALUE 'A' 重命名为 'B'
- php - 显示刀片文件的问题出现错误''count():参数必须是实现可计数的数组或对象''
- postgresql - Postgres - 为表分配自定义安全
- php - Symfony 5注册表验证不起作用
- android - 为什么在颤振上使用 TextField 后会显示 READ_EXTERNAL_STORAGE
- angular - instanceof 在 Angular 库中创建时返回 false
- javascript - 如何修复错误:迁移的 MD5 校验和失败 [1] npm ERR!代码 ELIFECYCLE npm 错误!错误号 1
- python - 如何用python子进程调用用shell编写的jq?