Introduction
json-schema-to-typescript compiles JSON Schema to TypeScript typings.
Check out the live demo.
INFO
This library is forked from https://github.com/bcherny/json-schema-to-typescript. Consider to support the original repo by giving it a star.
Installation
npm install @fumari/json-schema-to-typescriptpnpm add @fumari/json-schema-to-typescriptyarn add @fumari/json-schema-to-typescriptUsage
Transform your JSON Schema to TypeScript Definitions.
import { compile } from '@fumari/json-schema-to-typescript'
const mySchema = {
properties: [...]
}
compile(mySchema, 'MySchema')
.then(ts => console.log(ts))YAML and JSON files are also supported.
import fs from 'node:fs'
import { compileJsonFile, compileYamlFile } from '@fumari/json-schema-to-typescript'
compileJsonFile(fs.readFileSync('foo.json'), 'MyType').then(ts => fs.writeFileSync('foo.d.ts', ts))
compileYamlFile(fs.readFileSync('foo.yaml'), 'MyType').then(ts => fs.writeFileSync('foo.d.ts', ts))You can see Options for available options.
Handling $ref
You can either:
Pass a dereferenced schema, along with a
schemaToIdoption:tsimport { compile } from '@fumari/json-schema-to-typescript' import { refsPlugin } from '@fumari/json-schema-to-typescript/plugins/refs' const res = await compile(dereferenced, 'Person', { schemaToId: { get(schema) { // return the original $ref ID of given schema return '...' } } })Use the
refsPlugin()to enable built-in dereferencing:tsimport { compile } from '@fumari/json-schema-to-typescript' import { refsPlugin } from '@fumari/json-schema-to-typescript/plugins/refs' const res = await compile(schema, 'Person', { plugins: [refsPlugin()] })INFO
This requires
@apidevtools/json-schema-ref-parserto be installed.
Formatting
By default, it doesn't format the output TypeScript code.
You can install prettier and enable the Prettier plugin to format output:
npm install prettierpnpm add prettieryarn add prettierimport { compile } from '@fumari/json-schema-to-typescript'
import { prettierPlugin } from '@fumari/json-schema-to-typescript/plugins/prettier'
const mySchema = {
properties: [...]
}
await compile(mySchema, 'MySchema', {
plugins: [prettierPlugin()]
})Features
Supported
title=>interface- Primitive types:
- array
- homogeneous array
- boolean
- integer
- number
- null
- object
- string
- homogeneous enum
- heterogeneous enum
- Non/extensible interfaces
- Nested properties
- Schema definitions
- Schema references
- Local (filesystem) schema references
- External (network) schema references
- Add support for running in browser
- default interface name
- infer unnamed interface name from filename
deprecatedallOf("intersection")anyOf("union")oneOf(treated likeanyOf)maxItemsminItemsadditionalPropertiesof typepatternProperties(partial support)extendsrequiredproperties on objects- literal objects in enum
- referencing schema by id
- custom typescript types via
tsType
Unsupported
validateRequired- Custom JSON-schema extensions
Not expressible in TypeScript
dependencies(single, multiple)divisibleBy(example)format(example)multipleOf(example)maximum(example)minimum(example)maxProperties(example)minProperties(example)not/disallowoneOf("xor", useanyOfinstead)pattern(string, regex)uniqueItems(example)
Custom schema properties
tsType
Overrides the type that's generated from the schema. Useful for forcing a type to any or when using non-standard JSON schema extensions.
export const input = {
title: 'CustomType',
type: 'object',
properties: {
bar: {
description: 'Comparator function',
instanceOf: 'Function',
tsType: '(a: number, b: number) => number'
},
foobar: { $ref: '#/definitions/foobar' }
},
definitions: {
foobar: {
description: 'Map from number to string',
tsType: 'Map<number, string>'
}
}
}tsEnumNames
Overrides the names used for the elements in an enum. Can also be used to create string enums.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "WP_Post_Status_Name",
"type": "string",
"tsEnumNames": ["publish", "draft", "auto_draft"],
"enum": ["publish", "draft", "auto-draft"]
}FAQ
It is crashing on my giant file. What can I do?
- Disable code formatting if you've Prettier plugin enabled.
- Check if there's any issue resolving recursive schemas, welcome to open a bug report.
Further Reading
- JSON-schema spec: https://tools.ietf.org/html/draft-zyp-json-schema-04
- JSON-schema wiki: https://github.com/json-schema/json-schema/wiki
- JSON-schema test suite: https://github.com/json-schema/JSON-Schema-Test-Suite/blob/node
- TypeScript spec: https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md