An errors blows up when using the typings for the the Google Auth2 API - @types/gapi.auth2
. The compiler throws an error 1062
if I create a promise
This is the way I found to circumvent this error
private async loadGapiAuth() {
await new Promise((resolve) => gapi.load('client:auth2', resolve));
await new Promise((resolve) => gapi.auth2.init(GAPI_CONFIG).then(resolve));
}
then I can do this:
await this.loadGapiAuth();
const auth = gapi.auth2.getAuthInstance();
Edit: Answering my own question.
Google's documentation explicity says this:
Warning: do not call
Promise.resolve()
and similar with the result ofgapi.auth2.init()
. As the GoogleAuth object returned implements thethen()
method that resolves with itself, it will create an infinite recursion.
This means there will be trouble whether we're using Typescript or even plain Javascript.
So here Typescript is protecting the user from an infinite recursion. Whether or not that is it's intention, I don't know. The wording seems to suggest it's issue is entirely a typing problem or limitation of the compiler. But it's actually doing an important job.
TL;DR: The promise result is another promise which returns itself. The compiler error is guarding against infinite recursions.
It is dangerous to use Promise with any objects with it's own then()
method. See @gwilz answer. You will be trapped in an infinite loop!
One way to workaround is to actually remove then()
method:
async function getGapi() {
return new Promise<Omit<gapi.auth2.GoogleAuth, "then">>(resolve => {
...get auth object...
delete auth.then;
resolve(auth);
});
}
You just need to omit then
from the type.
async function getGapi() {
return new Promise<Omit<gapi.auth2.GoogleAuth, "then">>(resolve => {
});
}