TL;DR

JSON Schema をコンパイルして、TypeScript の型定義を生成するライブラリ。

仕組み

CLI の json2ts か、API の compile、compileFromFile で使う。スキーマの title がインタフェースの名前になり、required にないプロパティは省略可能になる。enum はリテラル型のユニオンになる。

例

json2ts -i foo.json -o foo.d.ts
json2ts -i 'schemas/**/*.json' -o types/

次のスキーマを入力すると、

{
  "title": "Example Schema",
  "type": "object",
  "properties": {
    "firstName": { "type": "string" },
    "age": { "description": "Age in years", "type": "integer", "minimum": 0 },
    "hairColor": { "enum": ["black", "brown", "blue"], "type": "string" }
  },
  "additionalProperties": false,
  "required": ["firstName"]
}

次の型が生成される。

export interface ExampleSchema {
  firstName: string
  /**
   * Age in years
   */
  age?: number
  hairColor?: "black" | "brown" | "blue"
}

関連

出典