https://github.com/mjwwit/tson-schema
A TypeScript API to create JSON-Schemas and TypeScript types
https://github.com/mjwwit/tson-schema
json-schema ts typescript
Last synced: 5 months ago
JSON representation
A TypeScript API to create JSON-Schemas and TypeScript types
- Host: GitHub
- URL: https://github.com/mjwwit/tson-schema
- Owner: mjwwit
- Created: 2019-02-25T19:40:46.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2022-02-11T17:26:31.000Z (over 4 years ago)
- Last Synced: 2025-12-27T21:08:05.647Z (6 months ago)
- Topics: json-schema, ts, typescript
- Language: TypeScript
- Size: 149 KB
- Stars: 3
- Watchers: 1
- Forks: 1
- Open Issues: 12
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# tson-schema
This project aims to bring you an easy way to create json-schemas and TypeScript types using a single API. This API is kept as close as possible to json-schema so you don't have to worry about learning yet another API. Support for new json-schema versions and new TypeScript versions is added on a best effort basis.
__This is a work in progress! Known missing json-schema features include:__
- `array.additionalItems`
- `object.additionalProperties`
- `$ref`
- JSON-Schema conditional schemas (`if`/`else`)
- Limited TypeScript support for:
- big enum schemas
- big allOf schemas
## Installing
```
npm install -S tson-schema
```
Or
```
yarn add tson-schema
```
## Usage
```ts
import * as t from 'tson-schema'
/**
* Array
*/
const numberArraySchema = t.array({
items: t.number({
minimum: 1
}),
minItems: 2,
uniqueItems: true
})
numberArraySchema.getSchema() // { type: 'array', items: { type: 'number', minimum: 1 }, minItems: 2, uniqueItems: true }
numberArraySchema.type // number[]
/**
* Object
*/
const objectSchema = t.object({
properties: {
req: t.string(),
opt: t.tuple({
items: [t.integer()]
})
},
required: ['req']
})
objectSchema.getSchema() // { type: 'object', properties: { req: { type: 'string' }, opt: { type: 'array', items: [{ type: 'integer' }] } }, required: ['req'] }
objectSchema.type // { req: 'string', opt?: [number] }
/**
* Enum
*/
const enumSchema = t.enum(['A', 2, 'C', 4])
enumSchema.getSchema() // { enum: ['A', 2, 'C', 4] }
enumSchema.type // 'A' | 2 | 'C' | 4
/**
* anyOf
*/
const anyOfSchema = t.anyOf([
s.const('A'),
s.integer()
])
enumSchema.getSchema() // { anyOf: [{ const: 'A' }, { type: 'integer' }] }
enumSchema.type // 'A' | number
```