How to use fetch in typescript

后端 未结 3 1174
慢半拍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

    If you take a look at @types/node-fetch you will see the body definition

    export class Body {
        bodyUsed: boolean;
        body: NodeJS.ReadableStream;
        json(): Promise;
        json(): Promise;
        text(): Promise;
        buffer(): Promise;
    }
    

    That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:

    import { Actor } from './models/actor';
    
    fetch(`http://swapi.co/api/people/1/`)
          .then(res => res.json())
          .then(res => {
              let b:Actor = res;
          });
    

提交回复
热议问题