How to generate DTOs for data objects?

Yesterday, we saw how to use json2ts to generate type definitions for our Angular applications. In addition, we saw that interfaces are optimal for performance reasons. Yet, the caveat with interfaces is that they can’t act as a Data Transfer Object (DTO) on their own to change the data you’re dealing with, nor do they perform any runtime checks.

As a result, some people might prefer to use Quicktype over json2ts as it has more configuration options when generating code from a JSON string:

As you can see, those options enable additional capabilities, such as using union types instead of enums (as recommended earlier), throwing errors if an object you’re parsing doesn’t have the right shape, and even some DTO operations such as using camel case instead of underscore in property names.

Of course, you can tweak that generated code and add additional DTO rules as needed.

Quicktype also supports languages other than TypeScript, so you could use that same tool to generate the server-side types for your data in Java, C#, or Python, for instance.

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.