4 ms·
For anyone using both TypeScript and JSON schemas, but wanting to use TypeScript as the source of truth, I highly recommend the following library: [ts-json-sche
by bertrand-caron 4y ago
For anyone using both TypeScript and JSON schemas, but wanting to use TypeScript as the source of truth, I highly recommend the following library: [ts-json-schema-generator](https://github.com/YousefED/typescript-json-schema https://github.com/YousefED/typescript-json-schema).
It does exactly what it says in the box: turns your TypeScript `types` / `interface` into machine-readable JSON schemas.
The library has a few open issues (does not deal well with some edge cases of composing Omit<> on sum types, and does not support dynamic (const) keys), but compared to manually writing JSON schemas, it's been amazing!
EDIT: I should add that the library supports adding further type constraints that are supported by JSON Schema but not by TS by using JSDoc (for instance, pattern matching on strings, ranges on numbers, etc.).
- mirekrusin 4y agoAdding extra transpilation step doesn't sound like a great solution. It also doesn't support inlined assertions, referring to existing classes, custom validations, opaque types etc.
- kristiandupont 4y agoI generally prefer Zod but in cases where I for one reason or another have to rely on JSON Schema, I use this package: https://www.npmjs.com/package/as-typed https://www.npmjs.com/package/as-typed which infers TS types directly from a such. No extra build steps required. I then use AJV for runtime validation.