Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/susisu/type-of-schema
Derives TypeScript type from JSON Schema
https://github.com/susisu/type-of-schema
Last synced: about 2 months ago
JSON representation
Derives TypeScript type from JSON Schema
- Host: GitHub
- URL: https://github.com/susisu/type-of-schema
- Owner: susisu
- License: mit
- Created: 2020-01-10T11:51:44.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2024-09-23T14:27:06.000Z (3 months ago)
- Last Synced: 2024-10-11T21:19:36.591Z (3 months ago)
- Language: TypeScript
- Homepage: https://npmjs.com/package/@susisu/type-of-schema
- Size: 194 KB
- Stars: 11
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# @susisu/type-of-schema
[![CI](https://github.com/susisu/type-of-schema/workflows/CI/badge.svg)](https://github.com/susisu/type-of-schema/actions?query=workflow%3ACI)
Derives TypeScript type from [JSON Schema](https://json-schema.org/)
## Installation
``` shell
# npm
npm i @susisu/type-of-schema
# yarn
yarn add @susisu/type-of-schema
# pnpm
pnpm add @susisu/type-of-schema
```## Usage
``` typescript
import type { TypeOfSchema } from "@susisu/type-of-schema";const schema = {
type: "object",
properties: {
"a": { type: "number" },
"b": { type: "string" },
},
required: ["b"],
} as const;// T = { a?: number; b: string }
type T = TypeOfSchema;
```Do not forget `as const` in the schema declaration. Without it, you will not get the full information of the schema.
## Supported Schemas
- `const`
- `enum`
- `null`
- `number` / `integer`
- `string`
- `boolean`
- `array` (`items` and `additionalItems`)
- `object` (`properties`, `required`, and `additionalProperties`)
- `oneOf`
- `allOf`## Limitations
For JSON Schema object types `S` and `T`, `S extends T` does not imply `TypeOfSchema extends TypeOfSchema`. In other words, a type derived from a schema can be inconsistent with what the schema actually describes. This can be observed, for example, when upcasting a schema containing `required`:
``` typescript
const schema1 = {
type: "object",
required: ["a"],
} as const;// T1 = { a: Value }
type T1 = TypeOfSchema;const schema2: {
type: "object";
required: ("a" | "b")[];
} = schema1;// T2 = { a: Value; b: Value }
// but b is actually not required
type T2 = TypeOfSchema;
```To avoid this, do always pass the original schema to `TypeOfSchema`.
## License
[MIT License](http://opensource.org/licenses/mit-license.php)
## Author
Susisu ([GitHub](https://github.com/susisu), [Twitter](https://twitter.com/susisu2413))