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.