Re:Parse, Don't Validate (2019)
by mirekrusin on Tuesday March 07, 2023 @07:54AM
(#35054767)
Adding 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.
Re:Parse, Don't Validate (2019)
by kristiandupont on Tuesday March 07, 2023 @07:57AM
(#35054787)
I 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 which infers TS types directly from a such. No extra build steps required. I then use AJV for runtime validation.
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.).