TypeScript Video Tutorial: Typing a Function Based on OpenApi
In this tutorial I suggest you explore the capabilities of Typescript a little more in depth to see how to create an advanced type based on an OpenApi definition.
The goal
The goal is to create a function that will call the API and return the results to us. The signature will look like this fetchAPI (baseUrl, endpoint, options)
and we want Typescript to check the parameters:
endpoint
must correspond to an entry point of our APIoptions.method
cannot be invalidoptions.query
must be an object that corresponds to what the API accepts at the query parameters leveloptions.params
will allow to add parameters in the URL (if the endpoint is/ post / {id}
for example we would expect thatid
is required)options.json
should be completed if the request expects a body inapplication / json
.- The response should automatically be typed according to the parameters received.
We want to automate this declaration as much as possible starting from an interface that will be generated by openapi-typescript from our OpenAPI definition file
The solution
To achieve the desired result we will have to use some advanced features of Typescript.
The generics
will allow you to create types which will have other types as parameters. For example, the possible methods will depend on the path:
type MethodsForPath = keyof paths (P)
The conditional types will allow you to check if a key exists in the interface to add a defined condition.
type SuccessResponseBody = P extends {responses: {"200": {"application / json": infer T}}}? T: undefined
We can also use utility types to avoid repetition.
// Find the type of a value in depth in a Get object
type Get = K extends ()
? T
: K extends (infer A, ... infer B)
? A extends keyof T
? Get
: D
: D;
Here is the type obtained for our function fetchAPI
(the code may be improved over time).
To improve
If you want to improve your ability to type your code you can try the types-challenges which offers you a series of exercises organized by level to practice.