3 ms·
I'd really like something like a compiler step/plugin to generate the validators from the declared typescript types.
by jrimbault 7y ago
I'd really like something like a compiler step/plugin to generate the validators from the declared typescript types.
- dlbucci 7y agoYeah, that's really something that feels like it should be a part of the language, because it would be so useful!
- eyelidlessness 7y agoIt's explicitly one of the language's non-goals[1]. > Add or rely on run-time type information in programs, or emit different code based on the results of the type system. Instead, encourage programming patterns that do not require run-time metadata. [1] https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals#non-goals https://github.com/Microsoft/TypeScript/wiki/TypeScript-Desi...
- williamdclt 7y agoI understand it (there's already enough to do at type level that runtime level is a non-goal), but types are purely indicative at IO boundaries. Validation still needs to happen
- eyelidlessness 7y agoThat's right. So since it won't be a part of the language, libraries like this are being developed.
- eyelidlessness 7y agoThis is basically that but in the opposite direction. It also has the advantage of being able to express validations that you can't express in the type system.
- randomchars 7y agoDo you have an example of the kind of validation couldn't be expressed in the type system?
- root_axis 7y agoMin or max length of an input. Any type of string validation like email or something similar that's validated via regex.
- eyelidlessness 7y agoroot_axis gave some good examples. Also types like `int` or `decimal` (which you can also pair with branded static types, but they don't actually guarantee anything other than their name. Really any kind of refinement you can imagine on primitive types.
- colinmcd 7y agoI should point out that there's nothing in Zod (yet) that isn't expressible in Typescript. I'll eventually get around to doing string/numerical validations (`.isEmail()`, etc) that go beyond TS but currently all functionality has an equivalent in TS.
- colinmcd 7y agoYou can generate JSON Schema from TS with this library: https://github.com/YousefED/typescript-json-schema https://github.com/YousefED/typescript-json-schema It's certainly conceivable to build an equivalent for Zod but you'll eventually want to validate types that aren't expressible in TS (i.e. Integer).
- IggleSniggle 7y agoThis looks like it generates JSON Schema, but not runtime validators?
- coffexx 7y agoFor that you could use something like ajv. Json schema has the advantage of being usable across different languages, but it does come with the overhead of maintaining those files and keeping it in sync with your other repos.