3 ms·
That's not entirely true. `z.string()` in Zod offers more than just type safety akin to TypeScript. TypeScript provides compile-time type checking, while Zod ad
by bythreads 2y ago
That's not entirely true. `z.string()` in Zod offers more than just type safety akin to TypeScript. TypeScript provides compile-time type checking, while Zod adds runtime validation and parsing.
For those unfamiliar:
`z.string()` effectively converts `mySchema` into a functional schema capable of parsing and validation.
For example:
`mySchema.parse("some data")` returns successfully.
`mySchema.parse(321)` throws an exception.
I've used it in places where you need runtime validation and in process verification - it works pretty well for that and you can extract the types from it via :
const A = z.string();
type A = z.infer<typeof A>; // string
Meaning if you define your types in zod first, and infer their types from that you get compile and runtime type checking.
---
It a bit of an overkill for nimble and fast code bases though - but works wonders for situations where in process proofing needs to be done, and in all honesty it isn't that big of a task to do this.
- Dylan16807 2y ago> Zod offers more than just type safety akin to TypeScript. TypeScript provides compile-time type checking, while Zod adds runtime validation and parsing. Well of course it offers more, or you wouldn't be installing a library. The problem is that even when you're expressing normal Typescript types, you have to use entirely different syntax. It's good that you can usually avoid double-definition, but it's still a big barrier that shouldn't be necessary.
- tommy_axle 2y agoThere's also typescript-to-zod that makes it possible to generate the zod schemas from your types.