How to use fetch in typescript

后端 未结 3 1177
慢半拍i
慢半拍i 2020-11-29 20:07

I am using window.fetch in Typescript, but I cannot cast the response directly to my custom type:

I am hacking my way around this by casting the Promise result to an

3条回答
  •  暖寄归人
    2020-11-29 20:56

    Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.

    That being said, the following works...

     fetch(`http://swapi.co/api/people/1/`)
          .then(res => res.json())
          .then((res: Actor) => {
              // res is now an Actor
          });
    

    I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...

    callBack: (response: any) => void
    

    But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...

    fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json())
      .then(res => {
          if (callback) {
            callback(res);    // Client receives the response as desired type.  
          }
      });
    

    So that a client can call it with a callback like...

    (response: IApigeeResponse) => {
        // Process response as an IApigeeResponse
    }
    

提交回复
热议问题