TypeSchema code generation explained

Christoph Kappestein
2 min readJan 19, 2022

This post explains more in detail how TypeSchema handles code generation. TypeSchema is a JSON format to describe data models in a language neutral format, which can be seen as an alternative to JSON Schema for i.e. usage at OpenAPI.

In the following examples we use Typescript as target language but these OOP concepts can be transferred also to other object oriented languages. At the examples we always show at a first a TypeSchema JSON file and then the generated output. You can reproduce also all examples by using our online code generator.

Simple

At this simple example we have a “Student” struct which contains some scalar properties. It is the most basic case which generates a simple interface for TypeScript.

Extends

In this case we have used the “$extends” keyword to defined that the student struct extends from the human struct. This is then also reflected at the generated code.

Reference

It is also possible to reference a different type. Note in TypeSchema it is not allowed to define a nested struct, that means you need to place all structs directly under the “definitions” keyword. This has the great advantage that we have a unique identifier for each struct and we can also easily reuse those structs.

Maps

In this example we create a simple map with a string value. In this case we define the map also under the “definitions” keyword, that means that the generator creates a dedicated class for this map.

Inline-Maps

In this example we use an inline-map, this means the generator simply uses the map implementation of your language and does not create a dedicated class, i.e. in TypeScript we use “Record” and in Java “HashMap”

Discriminator

This is a more complex examples which shows how to use a named discriminator, based on the provided type the location is either a Web or World instance.

Generics

At least we take a look how to handle generics. Through generics you can build types which contain placeholder. These placeholder can then be replaced with a different type by using the “$template” keyword. In this example we have a general Map and a specific StudentMap which passes the Student type to the map. This mechanic is really powerful to create types which can be reused in different environments.

Conclusion

I hope this post could provide a first overview how TypeSchema handles code generation. From our view it solves many problems which we currently have by using JSON Schema for code generation. For more details about TypeSchema please take a look at our specification. Also let us know if you have wrote a code generator in a specific language or if you plan to do this. To contact us you can either use the Github issues or our contact form.

--

--

Christoph Kappestein

I am a developer in the API space, currently working on Fusio an open source API management platform