How to generate type definitions for TypeScript?

This week, we have been looking at union types and the downsides of using any or unknown when we don’t have any accurate type information.

Today, let’s look at how to generate type information out of any JSON data. The first tool I want to mention is json2ts.com, a website where you can copy-paste any chunk of JSON syntax and get a fully-typed output of interfaces with inferred types and everything.

For instance, if I copy-paste the following JSON into json2ts:

We get the following set of interfaces ready to be used in our code:

The more data you give to json2ts, the more precise it is. For instance, if you give it an array of similar objects, json2ts can identify if some properties are optional or support multiple different types.

Also, it’s worth mentioning that interfaces are better than classes to describe type information because they do not get compiled into anything at all (like union types), thus bringing type safety to your code without making your production code bigger.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.