Member-only story
Inferring network requests’ return type: @express-typed-api
Even though choosing Typescript to develop an express web app provides type safety in both client and server, the network requests data remains untyped on both ends, complicating our attempts to keep a consistent code base 🤬 With that idea in mind I wrote @express-typed-api
, a library to help creating a type declaration for an express API so that it can be used to automatically infer the network requests’ return type from the client side. Here is how to use it.
The problem
Usually, when making a Web API network request via fetch
, we either settle with the any
type of the response payload or we explicitly cast it to the type we expect it to be.
Explicitly casting the payload’s type does provide type safety but it’s not ideal: it must be done for each different fetch call and, more importantly, it is not linked to the actual endpoint’s return type. When we change an endpoint’s return type, we also need to change the explicit casts accordingly for all of the endpoint’s fetch calls.
The idea behind @express-typed-api
is generating a type declaration for the express API, with no dependencies on the server side, and in a way that Typescript can tell the return type of…