Member-only story
Advanced Typescript by Example: API Service Manager
Implementing a generic API service manager with Typescript in React
This article will take you through the implementation of an API service manager written in Typescript to efficiently handle web services, consisting of two classes along with their associated types. These classes will be embedded within a Create React App project and tested at runtime within App.tsx
.
To gain clarity on the concepts talked about, the full project is available to browse through here on Github.
What is an API service manager?
The purpose of an API manager is to manage a web service, from its authentication to making requests and handling responses — that will either result in a successful or failed call. The manager must ensure type safety along the way, fully typing request and response objects. To prevent re-inventing the wheel, requests will be sent via Javascript’s native fetch()
API, that will work hand-in-hand with the manager.
In order to ensure objects can be typed at runtime, some classes and types will be generic. We will refrain from using the any
type throughout; any
is not helpful, especially when dealing with arbitrary data from remote services.
For a refresher on how generic types are used in Typescript, I published an article on the subject explaining what they are and how they are used:
As well as being generic, we also want classes to provide a fluent interface. This can be achieved by chain multiple function calls together like so:
const api =
new APIService()
.headers(...)
.method('POST')
.somethingElse(); ^
chaining methods in 1 expression
You most likely have used chained methods classes in other modules. They are useful for configuring objects like database queries, and in this case especially useful for configuring an API service, all in one…