Creating a fetch wrapper in Typescript
08:17 06 Oct 2019

I'm trying to create a wrapper for fetch in TypeScript but I can't get the typings right:

export interface ResponsePromise extends Promise {
  arrayBuffer(): Promise;
  blob(): Promise;
  formData(): Promise;
  json(): Promise;
  text(): Promise;
}

class Api {
  public get(url: string, params = {}): ResponsePromise {
    const body = new URLSearchParams(params).toString();
    return fetch(url, {method: 'GET', body});
  }
}

const foo = async () => {
  const api = new Api();
  await api.get('http://www.example.com').json();
}

Typescript Playground

typescript fetch-api