Generating JSON schemas from Typescript

07/06/2021

When storing json data in a database, the backing interface shouldn’t be changed without some consideration from the developer. One avenue of preventing unwanted changes is to use tools to generate JSON schemas from code. Then we can compare the generated schema with an older version to detect unwanted changes.

Example using ts-json-schema-generator:

export interface Book {
  author: string;
  pages: number;
  genre: BookGenre;
}

export enum BookGenre {
  ScienceFiction = "science_fiction",
  Adventure = "adventure",
}
./node_modules/.bin/ts-json-schema-generator -f 'tsconfig.json' --no-type-check --type 'Book' -o "book.json"

Which will produce:

{
  "$ref": "#/definitions/Book",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "Book": {
      "additionalProperties": false,
      "properties": {
        "author": {
          "type": "string"
        },
        "genre": {
          "$ref": "#/definitions/BookGenre"
        },
        "pages": {
          "type": "number"
        }
      },
      "required": ["author", "pages", "genre"],
      "type": "object"
    },
    "BookGenre": {
      "enum": ["science_fiction", "adventure"],
      "type": "string"
    }
  }
}

To detect unwanted changes we can simply use git.

git diff --output="schema.txt" --exit-code "book.json"