TypeScript API Contracts
This package provides a way to provide better type safety for Express servers and their clients.
This package is currently not used in production: this package aims to demonstrate the concept of API Contracts. Please use extreme caution when using this in production, as there is likely to be some unexpected behaviour.
The Problem
In Express, you define a route like this:
By default, properties like req.params
and req.body
are of type any
.
Similarly, the response body res.send
accepts any
.
Surely we can do better than this?
The client for this API is also loosely typed:
How do we know that /user
accepts a parameter username
, and what type is it?
What is the type of the response?
The Solution
API Contracts provides you with three useful types to give your server and client more type safety:
Contract
is used to define how your server and client will interact:
APIContract
takes yourContract
and type-checks your request parameters, body and response body:
ClientContract
takes yourContract
and type-checks your arguments and response:
// getUser : ({ username: string }) => { username: string; displayName: string }
Usage
- Install the package:
npm install --save-dev ts-api-contract
It's recommended to split your code into a Client package (containing the contracts and the client) and a Server package (containing Express), which ensures that unnecessary dependencies are not installed into the UI.
- For each endpoint, create a contract type in the client package:
// client/contracts.ts
You could type-check your contracts against
Contract
in the package, but this will cause some duplication in your definition:Instead, I'd recommend just reading
Contract
in this repository.
- Next, write your client method (in the client package, duh):
// client/client.ts ; ;
- Finally, write your route handler in your server package:
// server/server.ts ;app.patch"/user/:username", patchUser;
Problems?
This package aims to demonstrate the concept of API Contracts. If you've spotted a problem or would like to improve this, then submit a Pull Request!