Stop creating Typescript interfaces (manually)
Creating Typescript Interfaces doesn't have to be painful, it can be as simple as running a single command!
When integrating with 3rd party APIs that return JSON and we want to model this data structure in our project, creating these Typescript interfaces especially when the JSON is large, takes time.
Here is an example from GitHub’s API to get my repo JSON:
When I was working with the GitHub API a lot of JSON was returned, so I was keen to find a way to automate this process of creating the Typescript interfaces. I came across various tools, but the one that caught my eye was quicktype.
quicktype
generates strongly-typed models and serializers from JSON, JSON Schema, TypeScript, and GraphQL queries, making it a breeze to work with JSON type-safely in many programming languages.
Whilst it is easy to use it does create more code than I need for now, although I think it will be useful in the future. Let me show you:
Install the npm package globally:
npm install -g quicktype
Save the JSON response from the API, in my case GitHub to a JSON file. As you do not need this for your project, it can be saved to a temporary location.
I suggest not committing this JSON file as it will not be used and might cause some confusion on what these extra files are for (unless you need the example data for mocking, but that is another story). I add to the filename `*.tmp.json`, and in my global git ignore. I ignore any of these “tmp” files so they are not accidentally committed.
Using the command:
quicktype -s json -o <DESTINATION-TS-FILE> --lang ts <JSON-FILE>
The actual command looks like this:
quicktype -s json -o src/models/github/repo.ts --lang ts tests/mocks/repo.json
Two required parameters:
output/destination of the typescript file
input/source of the JSON file
These are the Typescript Interfaces that will be generated:
You don’t need to use all of the generated code. You can remove any Interfaces or items you will never use. In fact additional helper functions are included, but for now I have removed these from my code and from the image above.
Q. How do you make your Interfaces?
Conclusion
You should create types/interfaces for your project, but please do not use “any”! Being strict and saving your self pain later on doesn’t have to be difficult or time consuming, when we have tools that help us create them.
If you prefer to watch a video on this topic: