Member-only story

Adding type safety to fetch requests can be simpler than you think

Carles Capellas
3 min readJun 21, 2024

Writing a web app in Typescript provides type safety in both the client and the server but, what about the communication between the two sides? The payload of network requests remains untyped by default, boycotting our attempts to keep a consistent code base. With that idea in mind I wrote @typed-web-api, a minimalist approach to adding type safety to fetch requests. Here is how to use it.

typed-web-api comes in three parts. First we must create a type definition for the web API via @typed-web-api/common. The type definition is a description of all the endpoints, including their path, method and response type. Optionally we can specify their request payload type too.

This is what the type declaration would look like for a sample web API with three endpoints: POST /users/login, GET /users, GET /users/:userId.

  • Each endpoint must be listed using the /path_method format. This opinionated format is a simple convention that allows the library for validating the payload request type depending on the method.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Carles Capellas
Carles Capellas

Written by Carles Capellas

Always up for sport, somewhat obsessive about order and, over all things, enthusiastic about coding

No responses yet

Write a response