json-schema-to-typescript-cli
v3.0.0
Published
compile json schema to typescript typings
Downloads
12
Maintainers
Readme
json-schema-to-typescript
Compile json schema to typescript typings
[In Beta]: Bug reports appreciated!
Example
Input:
{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
},
"hairColor": {
"enum": ["black", "brown", "blue"],
"type": "string"
}
},
"required": ["firstName", "lastName"]
}
Output:
export interface ExampleSchema {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
hairColor?: "black" | "brown" | "blue";
}
Installation
npm install json-schema-to-typescript
or, to install the json-schema-to-typescript
CLI utility:
npm install -g json-schema-to-typescript
Usage
API
import {compileFromFile} from 'json-schema-to-typescript'
fs.writeFileSync('dist/foo.d.ts', await compileFromFile('src/foo.json'))
CLI
$ json-schema-to-typescript src/foo.json
... snipped output here, on stdout ...
$ json-schema-to-typescript src/foo.json dist/foo.d.ts
$
See /example for a fully working demo.
Tests
npm test
Todo
- [x]
title
=>interface
- [x] Primitive types:
- [x] array
- [x] homogeneous array
- [x] boolean
- [x] integer
- [x] number
- [x] null
- [x] object
- [x] string
- [x] homogeneous enum
- [x] heterogeneous enum
- [x] Non/extensible interfaces
- [ ] Custom JSON-schema extensions
- [x] Nested properties
- [x] Schema definitions
- [x] Schema references
- [x] Local (filesystem) schema references
- [ ] External (network) schema references
- [ ] Add support for running in browser
- [x] default interface name
- [ ] infer unnamed interface name from filename
- [x]
anyOf
("union") - [x]
allOf
("intersection") - [x]
additionalProperties
of type - [ ]
extends
- [x]
required
properties on objects (eg) - [ ]
validateRequired
(eg) - [x] literal objects in enum (eg)
- [ ] referencing schema by id (eg)
- [ ] clean up + refactor code
Not expressible in TypeScript:
dependencies
(single, multiple)divisibleBy
(eg)format
(eg)multipleOf
(eg)maximum
(eg)minimum
(eg)maxItems
(eg)minItems
(eg)maxProperties
(eg)minProperties
(eg)not
/disallow
oneOf
("xor", useanyOf
instead)pattern
(string, regex)patternProperties
(eg)uniqueItems
(eg)
Further Reading
- JSON-schema spec: http://json-schema.org/latest/json-schema-core.html
- 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