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

后端 未结 4 1230
陌清茗
陌清茗 2021-01-02 04:24

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

相关标签:
4条回答
  • 2021-01-02 04:32

    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();
    
    0 讨论(0)
  • 2021-01-02 04:46

    Edit: Answering my own question.

    Google's documentation explicity says this:

    Warning: do not call Promise.resolve() and similar with the result of gapi.auth2.init(). As the GoogleAuth object returned implements the then() 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.

    0 讨论(0)
  • 2021-01-02 04:47

    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);
      });
    }
    
    0 讨论(0)
  • 2021-01-02 04:55

    You just need to omit then from the type.

    async function getGapi() {
      return new Promise<Omit<gapi.auth2.GoogleAuth, "then">>(resolve => {
    
      });
    }
    
    0 讨论(0)
提交回复
热议问题