Typing `fetch` Responses in TypeScript

The `fetch` promise resolves to a generic `Response`, not your typed data. You must first parse the body with `.json()`, then assert the type of the resulting data. This is essential for all API calls.
`fetch` returns a generic `Response` promise, not a promise for your specific data type like `User`. TypeScript can't know what a remote server will send. You must first await the `Response`, check `response.ok`, then await `response.json()` and cast that result to your type. This is crucial for any JSON API call. The biggest footgun is trying to type the `fetch` call itself, like `fetch<User>(...)`; the type assertion belongs on the `.json()` result.
Read the original → developer.mozilla.org
- #typescript
- #fetch
- #web-api
- #type-safety
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.