LogRocket Blog

Generating JSON Schema from TypeScript types

thumbnail

Generating JSON Schema from TypeScript types

This article explores how to generate and work with JSON Schema using TypeScript types. JSON Schema provides a way to define the structure of JSON data and ensure that the wire data our application is accepting is formatted correctly.

Project setup

To generate JSON Schema from TypeScript types, we need to set up a project and install the necessary packages.

Writing a TypeScript interface

We define a TypeScript interface that represents the structure of the data we want to generate JSON Schema for.

Using the package

We use a package that can convert TypeScript types into JSON Schemas. By running a command, we can generate a JSON Schema for our TypeScript type.

Using the generated JSON Schema

With the generated JSON Schema, we can specify that any object claiming to be of that type should have certain properties. We can then use the generated JSON Schema to validate the wire data and ensure it conforms to the expected structure.

Adding a middleware function to validate our data

We add a middleware function to our application that uses the JSON Schema to validate the incoming data. If the data does not conform to the schema, an error response is returned.

By generating JSON Schema from TypeScript types, we can ensure that our wire data adheres to a strict schema and catch any errors early in the development process.