10 ms·
Zod: TypeScript-first schema validation with static type inference
- threatofrain 2y agoThis is just a link to the front page of possibly the #1 most popular type validation library in the ecosystem? Anyways, ya'll might want to check out up-and-coming Valibot, which has a really nice pipe API. https://valibot.dev https://valibot.dev
- sergiotapia 2y agoA whole lot of yapping and ZERO code on the homepage. Authors should remove 90% of the stuff on that landing page, jesus! also since zod is the de facto validation lib, might be worth a specific page talking about why this vs zod. even their migration from zod page looks nearly identical between the two packages.
- petesergeant 2y agoOn the front page there is a prominent section addressing the differences from Zod, which appear to be “much better performance”
- rjknight 2y agoValibot is really nice, particularly for avoiding bundle size bloat. Because Zod uses a "fluent builder" API, all of Zod's functionality is implemented in classes with many methods. Importing something like `z.string` also imports validators to check if the string is a UUID, email address, has a minimum or maximum length, matches a regex, and so on - even if none of those validators are used. Valibot makes these independent functions that are composed using the "pipe" function, which means that only the functions which are actually used need to be included in your JavaScript bundle. Since most apps use only a small percentage of the available validators, the bundle size reduction can be quite significant relative to Zod.
- lolinder 2y agoIs there a reason why tree shaking algorithms don't prune unused class members? My IDE can tell me when a method is unused, it seems odd that the tree shaker can't.
- everforward 2y agoDoes that work for all class members? I think I've only ever seen that on private members, though I don't know whether that's because it's so much easier to check whether a private member is used or because an unused public member isn't an issue for eg a library. This feels like an issue that reduces down to the Halting Problem, though. Halting is a function that could be made a member of a class, so if you could tell whether that method is used or not then you could tell whether the program will halt or not. I think it's one of those things that feels like it should be fairly easy, and it's really really not.
- lolinder 2y agoComparing this to the halting problem isn't really meaningful here because even if you could make a full mapping (which yours isn't), you can prove that a rather large subset of programs halt, which is good enough for a tree shaker. I don't need to be able to eliminate every single unused function in every situation, but if I can prove that certain functions are unused then I can delete just those functions. We're already doing this regularly with standalone functions, so my question is just why this isn't done with class members.
- everforward 2y agoAh, I see your question now. Prototypes maybe? I’m not nearly a good enough JS dev to have a reasonable guess at that specifically. Being able to access class members using square bracket syntax with a variable also seems like it would make it really difficult to prove that something isn’t used. I’m thinking something unhinged like using parameters to build a string named after a class member and then accessing it that way. Dunno, I would be curious if someone has a definitive answer as well.
- crooked-v 2y agoValibot also has much, much more efficient type inference, which sounds unimportant right up until you have 50 schemas referencing each other and all your Typescript stuff slows to a molasses crawl.
- zztop44 2y agoAgreed. I recently moved a production app from Zod to Valibot for exactly this reason. I still slightly prefer Zod’s syntax but the performance issues were absolutely killing us.
- Escapado 2y agoNot only that, runtime schema validation was also way faster in my last project for larger arrays of complex objects with lots of union types. Went from 400ms to 24ms all else being equal. Since our validation was running on every request for certain reasons this made a huge difference in perceived performance for our users and less load on our servers.
- Timon3 2y agoI recently stumbled onto this when looking for alternatives, and though it might sound a bit extreme: the style of documentation means I'll never consider it for any project. It's strange and honestly somehow unnerving to read documentation written from a first-person perspective. Is there some good reason for this that I'm missing? Or am I just crazy and this isn't an issue for anyone else?
- Bjartr 2y agoI only see second-person "you" and not first-person "I" in the linked documentation. Am I missing what you intended to point out? In any case, this might actually be a good use for an LLM to post-process it into whatever style you want. I bet there's even a browser extension that could do it on-demand and in-place.
- Timon3 2y agoReally? For example under "Main concepts" on the "Schemas" site[0], I see stuff like this: - I support the creation of schemas for any primitive data type. - Among complex values I support objects, records, arrays, tuples as well as various other classes. - For objects I provide various methods like pick, omit, partial and required. - Beyond primitive and complex values, I also provide schema functions for more special cases. Same for "Mental model", "Pipeline", "Parse data", "Infer types", "Methods" and "Issues" - I'll assume the other sections also follow this style. That's all not showing up for you? While the LLM suggestion is nice, it's not something I'm comfortable with unless hallucinations are incredibly rare. Why would I use a library whose documentation I have to pass through an unreliable preprocessor to follow a normal style? [0]: https://valibot.dev/guides/schemas/ https://valibot.dev/guides/schemas/
- prophesi 2y agoIf they're part of Hacktoberfest, editing those pages to drop the first person perspective sounds like a pretty useful first contribution.
- 2y ago
- kaoD 2y agoDoes/will this correctly handle `| undefined` vs `?`, i.e. correct behavior under `exactOptionalPropertyTypes`? Zod doesn't (yet[0]) and it's been a pain point for me. [0] https://github.com/colinhacks/zod/issues/635 https://github.com/colinhacks/zod/issues/635
- x1000 2y agoI ran into exactly same pain point which was enough to nullify the benefits of using zod at all.
- aleclarsoniv 2y agoTypeBox[1] differentiates between optional and undefined. [1]: https://github.com/sinclairzx81/typebox https://github.com/sinclairzx81/typebox
- gkiely 2y agoIt does: https://valibot.dev/guides/optionals/#use-in-objects https://valibot.dev/guides/optionals/#use-in-objects import * as v from 'valibot'; const OptionalKeySchema = v.object({ key: v.optional(v.string()) }); type t1 = v.InferInput<typeof OptionalKeySchema>; // { key?: string } const UndefinedKeySchema = v.object({ key: v.undefinedable(v.string()) }); type t2 = v.InferInput<typeof UndefinedKeySchema>; // { key: undefined }
- mightyham 2y agoI'm currently using valibot and the author's associated modular form library in a production app and can vouch that it's been very pleasant to work with.
- Eric_WVGG 2y agoIs Valibot's error handling any good? Zod's is… like punishment for a crime I wasn't aware that I had committed.
- hyperbrainer 2y agoMaybe OP is one of the lucky 10,000. https://xkcd.com/1053/ https://xkcd.com/1053/
- deleted 2y ago[deleted]
- diggan 2y agoAs someone who never jumped onto the TypeScript hype-wagon, what is this for? Is this something like clojure.spec by for TypeScript so you can do runtime validation of data instead of compile-time validation? Basically joi (https://joi.dev/api/?v=17.13.3 https://joi.dev/api/?v=17.13.3) but different in some way?
- VoidWhisperer 2y agoCorrect on the part of it being a runtime validation of data library (I can't as easily speak to whether or not it is similar to joi, never used it)
- _fat_santa 2y agoI think the killer feature of Zod is type inference. Not sure if Joi has support for it yet but you can take a zod schema and wrap it in `z.infer` to get the typescript type. Personally I use zod in my API for body validations, it's super nice to write the schema then just use `type Body = z.infer(schema)` to get the TS type to use inside the code.
- threatofrain 2y agoThat's table stakes for this niche.
- naberhausj 2y agoI've not used either, but it appears to be similar to JOI, yes. The main distinction is that ZOD allows you to extract a TypeScript type from your schema. This means you get both compile-time and run-time type checking.
- valbaca 2y agoyep. Typescript is build-time validation, but in the end TS is "just JS" Zod provides runtime validation (and also works well with TS)
- molszanski 2y ago
- vorticalbox 2y agoAt work I have used zod, myzod, joi though I have settled on class-validator as it ties in with nestjs really well.
- timpetri 2y agoLooking around on Twitter and repos in the OSS community, it appears that Zod is now almost always favored over yup, despite an almost identical API. Curious to hear what people think if they've worked with both. We went with Yup early on at my company, and now that's what we use for consistency in our codebase. I haven't personally found it to be lacking, but some of the logic around nulls and undefined always lead me back to the docs.
- roessland 2y agoMy company used Yup initially but we moved to Zod to be able to infer types from schemas. For example, API response payloads are Zod schemas. OpenAPI components are also generated from Zod schemas. There are some performance issues, and WebStorm is struggling, which forced me over to VS Code. But overall pretty happy.
- greener_grass 2y agoSome tech influencers pushed Zod - that's basically the entire story
- psadri 2y agoOne thing to note about zod - it clones objects as it validates (parses) them. Eg z.array(z.object()) with an array of 10k objects will result in 10k cloned objects → slow.
- molszanski 2y agoI would suggest https://arktype.io/ https://arktype.io/. Much faster on my project
- leontrolski 2y agoFor those of you from a Python background - this is basically "Pydantic for Typescript". See also trpc - cross client/server typing using zod under the hood - https://trpc.io/ https://trpc.io/
- brap 2y agoI always found it pretty awkward that you even need libraries like this. A limitation of TS I suppose.
- bluepnume 2y agoYou find it weird that a type system doesn't do runtime validation? Is that common in many other languages?
- yen223 2y agoOther statically-typed languages do have to deal with the problem of parsing external objects. In my experience, none of them have parsers as good as Zod in terms of ergonomics.
- dhruvrajvanshi 2y ago> Other statically-typed languages do have to deal with the problem of parsing external objects. Well that's just blatantly not true. Which languages are you thinking of? I'm sure I'm misunderstanding what you said. I can't think of a single server side language that doesn't have to parse external untyped objects. That's where these serialization libraries come into play. For example, in Kotlin, you declare a data class and mark it as @Serializable and it generateds `toJSON/fromJSON` for you. IMO it's a much better experience than Zod.
- yen223 2y ago> I can't think of a single server side language that doesn't have to parse external untyped objects. That's what I said too. > For example, in Kotlin, you declare a data class and mark it as @Serializable and it generateds `toJSON/fromJSON` for you. IMO it's a much better experience than Zod. If the JSON object matches the data class exactly, the Zod parser and the Kotlin Serialization parser and Jackson and all those other JSON parsers are similar in complexity. However, where Zod shines is if the JSON object doesn't match your domain class exactly, e.g. you want to parse a JSON number into a Date, or you want to parse a string field into some custom domain object. In those cases, in zod this is a one-liner with `.transform(...)`. Other libraries will require all kinds of weird workarounds to support this. The other thing Zod does really well is composition, i.e. making new schemas out of existing schemas. Something like this is difficult to express in most language's parser frameworks: const User = z.object({id: z.string(), username: z.string(), ...}) const CreateUserPayload = User.omit({id: true}) // Same as user, but without the id field const UpdateUserPayload = CreateUserPayload.partial() // Same as CreateUserPayload, but now all the fields are optional
- dhruvrajvanshi 2y agoI wonder about a Typescript with alternate design decisions. The type system is cool and you can do a lot of compile time metaprogramming. However, when there's a type error in computed types, it's a nightmare to visually parse type { foo: ... , bar: ..., ... } can't be assigned to type { foo: ..., bar: ... }. type { foo: ... bar: ..., ... } is missing the following properties from { foo: ..., bar: ..., ... } Apart from repeating roughly the same type 4 times (which is a UX issue that's fixable), debugging computed types requires having a typescript interpreter in your head. I wonder if we had nominal runtime checked types, it could work better than the current design in terms of DX. Basically, the : Type would always be a runtime checked assertion. Zod certainly fills that gap, but it would be nicer to have it baked in. The type system would not be as powerful, but when I'm writing Kotlin, I really don't miss the advanced features of Typescript at all. I just define a data class structure and add @Serializable to generate conversions from/to JSON.
- rlp 2y agoThis is my exact experience. TypeScript seemed to hit a complexity sweet spot about 5 years ago, then they just kept adding more obscure stuff to the type system. I find that understanding TypeScript compiler errors can be almost as difficult as understanding C++ template errors at times.
- phplovesong 2y agoThis. Haxe is a more sane TS alternative in 2024.
- jadbox 2y agoIt's Haxe still been actively developed? I loved it back in the day. The blog hasn't had an update in years.
- phplovesong 2y agoIt is. And only getting better SLOWLY by each iteration. The thing i love about Haxe that once you use it, your installed version is not legacy in a month (unlike npm/typescipt ecosystem). Haxe is fully working, and does not need a lot of "new" features. More news about Haxe can be found here: https://haxe.io/ https://haxe.io/ (the old blog is not updated AFAIK)
- molszanski 2y agoI very much enjoy more an alternative. Sadly much less hyped https://arktype.io/ https://arktype.io/
- threatofrain 2y agoWhat do you like most about arktype?
- molszanski 2y agoI think the homepage kinda sums it up. It just works and has OP performance, stability and quality
- ecuaflo 2y agoWhen there’s feature parity, what’s the next differentiator for you? For me, performance. Though I admit another important aspect is community adoption. If your 3rd-party dependency uses zod internally, well now you’re bundling in both, and the added network latency probably negates any performance improvement you were getting in a web app. That’s why I wish libraries would use something more generic that allows you to dependency-inject what you’re already using, like https://github.com/decs/typeschema https://github.com/decs/typeschema
- aleksiy123 2y agoDoes anyone have a nice combination of tooling for typed handlers + client generation. Thinking maybe Zod + Zod open API. Really looking to replicate similar spec first workflow similar to protobuf services. https://typespec.io/ https://typespec.io/ also looks promising but seems early.
- bjacobso 2y agoI think you are looking for https://ts-rest.com/ https://ts-rest.com/
- kaoD 2y agoNice. I'm looking to migrate away from a legacy custom framework over Express and this could help. If someone has tried both, can anyone share how it compares with tRPC[0]? [0] https://trpc.io/ https://trpc.io/
- bjacobso 2y agoFrom my understanding trpc is very similar, however, the rpc mechanism is not a standard. ts-rest produces openapi schemas and speaks REST over http, as well as a typed client. That being said, I am actually slowly migrating off ts-rest and adopting @effect/schema and @effect/platform/HttpApi, I foresee this being the direction the typescript ecosystem heads in over the next few years. However, the APIs are not stable yet and it has a bit of a learning curve, so would not adopt lightly
- AWebOfBrown 2y agoI really wanted to adopt tRPC but the deal breaker was it being opinionated on status codes without allowing configurability. Because I needed to meet an existing API spec, that meant ts-rest was a better option. I think there's an aditional option with a native spec generator in frameworks like Hono, and maybe Elysia.
- mnahkies 2y agoMy tool https://openapi-code-generator.nahkies.co.nz/overview/about https://openapi-code-generator.nahkies.co.nz/overview/about generates typed handlers based around koa (routing, req/res validation using zod) from openapi 3, as well as typed clients with optional zod validation using fetch/axios. It also supports typespec using their transpilation to openapi 3 tooling
- bearjaws 2y agoOne of the brilliant decisions of the AI SDK from Vercel was to use Zod. It makes tool calling and chaining very robust, despite how finicky LLMs can be.
- bjacobso 2y agozod is great, but I have been moving to @effect/schema and think it deserves a mention here. @effect/schema is the evolution of io-ts, which originally inspired zod. It supports decoding as well as encoding, and fits natively into the rest of the effect ecosystem. https://effect.website/docs/guides/schema/introduction https://effect.website/docs/guides/schema/introduction It does come with the cost of importing effect, so might not be the best in certain scenarios. However, there are smaller options than zod if that is a concern.
- obeavs 2y agoYep. Effect is so cool. The ability encode AND decode is tomorrow's standard. With all the work they're doing on durable workflows, hard to imagine that 2025 is anyone else's year.
- dgellow 2y agoZod is fantastic, we use it pretty extensively at Stainless. Definitely one of my favorite JS library. Not calling it a parser combinator was a really good marketing move
- Stoids 2y agoThe fragmentation around runtime validation libraries is pretty crazy. The fact that half these comments mention some alternative library that mimics almost the exact API of Zod illustrates that. It is filling a necessary shortcoming in the gradual typing of TypeScript, and using validator schema types to power other APIs generic inference is powerful. I am optimistic about an obvious leader emerging, or at least a better story about swapping between them more easily, but a bit annoying when trying to pick one to settle on for work that I have confidence in. That being said, Zod seems like the community favorite at the moment.
- skybrian 2y agoYes, it's annoying. I share your optimism. This is how the JavaScript (and now TypeScript) community figures things out. Note that TypeScript had competitors, too. It got better. Zod has an early lead and is good enough in a lot of ways, but I'm not sure it will be the one. Perhaps someday there will be a bun/deno-like platform with TypeScript++ that has validation merged in, but it's probably good that it's not standardized yet.
- root_axis 2y agoI prefer typebox because it uses JSON schema. As far I'm aware it's otherwise on par with Zod, but I might be unaware of some capabilities of Zod that typebox lacks.
- steve_adams_86 2y agoI love Zod, but recently I've been converting to Effect's Data and Schema modules. Previously I liked a combination of Zod and ts-pattern to create safe, pattern matching-oriented logic around my data. I find Effect is designed far better for this, so far. I'm enjoying it a lot. The Schema module has a nice convention for expressing validators, and it's very composable and flexible: https://effect.website/docs/guides/schema/introduction https://effect.website/docs/guides/schema/introduction There are also really nice aspects like the interoperability between Schema and Data, allowing you to safely parse data from outside your application boundary then perform safe operations like exhaustively matching on tagged types (essentially discriminated unions): https://effect.website/docs/other/data-types/data#is-and-match https://effect.website/docs/other/data-types/data#is-and-mat... It feels extremely productive and intuitive once you get the hang of it. I didn't expect to like it so much. I think the real power here is that these modules also have full interop with the rest of Effect. Effects are like little lazy loaded logical bits that are all consistent in how they resolve, making it trivial to compose and execute logic. Data and Schema fit into the ecosystem perfectly, making it really easy to compose very resilient, scalable, reliable data pipelines for example. I'm a convert. Zod is awesome if you don't want to adopt Effect wholesale, though.
- bjacobso 2y agoI've had a very similar experience, and have been slowly moving from zod and ts-rest to @effect/schema and @effect/platform/HttpApi as well as migration to Effect Match from ts-pattern. There is a learning curve but its a pretty incredible ecosystem once you are in it for a bit. I think the real turning point was typescript 5.5 (May 2024). The creator of typescript personally fixed a bug that unlocked a more natural generator syntax for Effect, which I think unlocks mainstream adoption potential. https://twitter.com/MichaelArnaldi/status/1785061608894451725 https://twitter.com/MichaelArnaldi/status/178506160889445172... https://github.com/microsoft/TypeScript/pull/58337 https://github.com/microsoft/TypeScript/pull/58337
- morbicer 2y agoI feel like Effect is today's Ramda. So cool but it's going to be regretted by you and people coming after you in few years. Me and my team reverted to more stupid code and we are happier.
- BenoitP 2y agoAnd thus custom validation goes to json, completing a what is old is new again cycle. After XML/XSD, after CORBA.
- agluszak 2y agoCould someone explain to me what problem exactly Zod solves? Why do you need to do `type User = z.infer<typeof User>;` instead of declaring a class with typed fields and, idk, deriving a parser for it somehow? (like you would with Serde in Rust for example). I don't understand why Zod creates something which looks like an orthogonal type hierarchy. For context: I come from the backend land, I enjoy strong, static typing, but I have very little experience with JS/TS and structural typing
- xmonkee 2y agoThe User object in your example is used to parse the data. Its the “somehow” part of your question. There is no way to go from a type to data in typescript (there is no runtime awareness of types whatsoever) so zod solves this by you writing the zod object and then deriving the type from it. Basically you only have to weite one thing to get the parser and the type.
- outlore 2y agoThe “type User =“ statement creates a TypeScript type from the zod schema, which can be useful when passing that definition around to functions The schema object is useful for runtime validation, e.g. User.parse(). this is handy when validating payloads that come over the wire that might be untrusted. the output of the “parse()” function is an object of type User you can kind of think of it like marshaling Json into a struct in Go :)
- _heimdall 2y agoZod offers runtime type validation where typescript only does this at build time. You can also use it for data normalization, safely parsing date strings to Date objects for example.
- cheriot 2y agoI used it to validate data from config files matched the schema. I imagine it could be useful for other sources of suppose-to-be-structured data like an http body.
- arzig 2y agoThere’s no macro system in TS that could analyze the type to build the parser. So, you work the other way and build the parser and then produce the type from that.
- Cu3PO42 2y agoZod has been a great boon to a project I've been working on. I get data from multiple sources where strong types cannot be generated and checking the schema of the response has caught a great number of errors early. Another feature that I use intensively is transforming the response to parse JSON into more complex data types, e.g. dates but also project-specific types. In some situations, I also need to serialize these data types back into JSON. This is where Zod lacks most for my use-case. I cannot easily specify bidirectional transforms, instead I need to define two schemas (one for parsing, one for serializing) and only change the transforms. I have added type assertions that should catch any mistakes in this manual process, but it'd be great if I didn't have to keep these two schemas in sync. Another comment mentioned @effect/schema [0], which apparently supports these encode/decode relationships. I'm excited to try it out. [0] https://effect.website/docs/guides/schema/introduction https://effect.website/docs/guides/schema/introduction
- epolanski 2y agoI use schema extensively and I can tell you it hits the sweet spot for your use case. We have lots of similar use cases.
- aleclarsoniv 2y agoTypeBox[1] also supports bi-directional transforms. [1]: https://github.com/sinclairzx81/typebox https://github.com/sinclairzx81/typebox
- Cu3PO42 2y agoThank you for the pointer! I will certainly consider TypeBox as well when the time comes to migrate.
- n00bskoolbus 2y agoSomething cool that I can't remember if it was posted on HN at one point or I stumbled across when looking for alternatives to yup but this repo has been compiling a bunch of different benchmarks for runtime validation of ts validation libraries. Obviously to some degree the performance is arbitrary when you're reaching millions of operations per second but on the flipside their benchmarks are against rather data. Would be interested to see comparison of either more nested data or otherwise complex. Maybe something to look at in my spare time. https://moltar.github.io/typescript-runtime-type-benchmarks/ https://moltar.github.io/typescript-runtime-type-benchmarks/
- matt7340 2y agoI really like the Decoders library for this. Similar in function to Zod, but a more Elm inspired approach - https://decoders.cc/ https://decoders.cc/
- aleclarsoniv 2y agoI'd recommend TypeBox[1] as an alternative, which has a runtime “compiler” for generating optimized JS functions from the type objects. It also produces a JSON schema, which can be useful for generating API docs and API clients if needed. It also has a companion library[2] for generating TypeBox validators from TypeScript definitions, which I'm currently using in an RPC library I'm working on. [1]: https://github.com/sinclairzx81/typebox https://github.com/sinclairzx81/typebox [2]: https://github.com/sinclairzx81/typebox-codegen https://github.com/sinclairzx81/typebox-codegen
- JasonSage 2y agoWe are moving from Zod to TypeBox because there’s a lot of inflexibility in Zod’s extensibility story that we’re able to get past in TypeBox. After doing a deep-dive comparison, I’m left wondering why to ever choose Zod over TypeBox.
- wruza 2y ago[2] Man why doesn’t it have a cli tool?? Wouldn’t it be nice to :'<'>!typeboxify a selection.
- maxthegeek1 2y agoLikewise we use typebox for everything in our project (open source customer.io alternative). https://github.com/dittofeed/dittofeed/blob/main/packages/isomorphic-lib/src/types.ts https://github.com/dittofeed/dittofeed/blob/main/packages/is...
- shadowfiend 2y agoWhat’s the go-to reason to use this over ajv? In particular, being rooted in JSON Schema feels like a pretty big win tooling-wise and interop-wise.
- petesergeant 2y agoYou can reflect TS types out of it. There are 3rd party libraries to generate JSON Schemas from Zod objects, which is helpful if you have non-TS clients you want to support
- shadowfiend 2y agoAjv has supported that for at least a couple of years afaik, and consumes JSON Schema natively which is good for consuming other APIs, not just feeding external clients—its base data format is interoperable, basically. That’s mostly why I’m curious about the lack of mention :)
- petesergeant 2y agoYou can’t reflect types out of Ajv. TS types are compile-time, Ajv consumes JSON schemas at runtime.
- shadowfiend 2y agoYou are mistaken: https://ajv.js.org/guide/typescript.html#utility-types-for-schemas https://ajv.js.org/guide/typescript.html#utility-types-for-s...
- petesergeant 2y agoThat seems to show that you have to bring your own types for JSON Schema still, as evidenced by their example both explicitly defining the interface and then passing that it as an argument. I wasn’t aware however of JSON Type Definitions, which hadn’t been invented last time I released software with Ajv, but it does appear to be able to reflect those as well as validate from them, so thank you for showing me that.
- stevebmark 2y agoTo this day Zod is still a huge PITA to use. See https://github.com/colinhacks/zod/issues/372 https://github.com/colinhacks/zod/issues/372
- anonzzzies 2y agoPerhaps one day we will have properly working wasm stuff and we can forget about all these terrible because-typescript-sucks-because-js-sucks libraries.
- progx 2y agoAha, and how you program wasm?
- anonzzzies 2y agoWikipedia; The main goal of WebAssembly is to facilitate high-performance applications on web pages, but it is also designed to be usable in non-web environments.[7] It is an open standard[8][9] intended to support any language on any operating system,[10] and in practice many of the most popular languages already have at least some level of support.
- hombre_fatal 2y agoHow does this have to do with a validation library? These exist for every language so that you can validate unknown data, e.g. user data coming over the wire or data from an external process.
- anonzzzies 2y agoA proper language would just compile that in; aka when something doesn't fit the struct, it dies. That's what zod does because typescript cannot; you can have lovely and complex types until you see blue in the face, but if they are runtime, they pass because it's js. That doesn't happen in other languages. Try some Rust or Haskell and try to stuff in via REST something that doesn't fit in the struct you defined. With typescript it happily continues unless you use all kinds of crap , like Zod, to validate again. Why not make it so typescript has options to compile to zod etc with a flag for runtime? I seriously don't understand why I spend time on writing this as the fanbois who never tried anything nice that doesn't need this think it's the best thing. You all loved left pad and this is no different.
- kpmah 2y agoI recently came across (but haven't yet used) Typia, which appears to let you do validation with regular TypeScript syntax: https://github.com/samchon/typia https://github.com/samchon/typia
- 015a 2y agoZod is very good. No further comment necessary.
- kuon 2y agoI'm a rust,zig and elixir developer and I had to work on a large typescript project that use zod. I felt like I was being punished for everything. (Maybe some things were project specific so I am not saying this as an absolute) It's slow, syntax is horrible, error are obscure super long lines, it can compile and explode later (which is what elixir does, except elixir will happily restart and recover)... Elixir is based on duck typing mostly, but it works very well because you just pattern match your data when you use it. Rust is very strict and can have cryptic errors, but as everything is baked in the language it is way easier to manage. I am not saying this to be snob about typescript and JS, but I really felt pain when working with that ecosystem, and I wonder if I'm old and stupid or if those tools are really half baked and over complicated.
- joshribakoff 2y ago>elixir will just recover Thats not true. It just crashes the “sub” process and if the parent process spawns the sub process again with the same inputs its just going to crash again. Are you aware you can also try/catch your errors in typescript? The whole point of the library is to validate something at runtime so of course it is going to blow up. There are also API methods that simply return a boolean instead of crashing if it fails validation. You can then use type guarding and narrowing of the type.
- ForHackernews 2y agoErlang/elixir is built around a "let it crash" model. The idea is that the system as a whole is robust, not individual processes.
- Dumble 2y agoIf your i.e. server process kills itself when validating data, that's not the Problem of ZOD. The violation failing is an expected case, that is the use case for such a library.
- evilduck 2y agoAn infinite loop of crashing isn't very useful though. "Let it crash" doesn't lead to a whole system being robust all by itself since you can also just say "let it throw exceptions" in just about any language. Erlang's whole-system robustness emerges when far more than just how you handle exceptions and crashes is implemented to support things that crash. It expects parallel processes and even redundant computing infrastructure to exist to handle those things that are crashing, and hopefully those redundancies behave in a way that doesn't also crash in the same way. Erlang only achieves its robustness because nobody really chooses Erlang without also knowingly buying into the entire setup that it requires to succeed. And if they don't then it won't actually achieve that robustness and succeed in that way. The phone systems that Erlang's design emerged from naturally had these parallelism and distributed system properties that they could leverage and build on. Running Erlang on a single core SBC like to display virtual signage and limiting it to a single thread and not letting it have any redundancy in any way and then taking the approach of "let it crash" is not going to create a famously robust Erlang setup either, it's just going to create an Erlang-powered signage system that crashes and halts the same as any other runtime would. Erlang/OTP is a physical systems building and software design approach that you can't just put anywhere or bolt onto any arbitrary thing. You're not going to build an OTP-like Single Page Application because if you reliably crash the browser tab's process every time you start up, it's just going to keep crashing no matter how many times you refresh the page.
- disintegrator 2y agoWe build our TypeScript SDK code generator on Zod. So data coming from the user or API is validated and transform using generated Zod schemas. It's a fantastic library with some caveats specifically with Zod v3: - Yes, it doesn't tree-shake well because of the chaining API. We accept this tradeoff because there's a lot of value coming from those kilobytes. - In pure benchmarking numbers, it's nowhere near the fastest validator but I would wondering where you're using Zod and needing millions of operations per second. In my world, the network absolutely diminishes any performance benefits of the fastest validation library. - It can slow down typescript type checking in extreme cases. This one is aimed at those folks that have a large number of very complex schemas. A good majority will not encounter this problem. I say all this but on the flip side, I will pick Zod again and again because it has the biggest community behind and is well on its way to having ecosystem around e.g. with react-hook-form, trpc and other framework integrations. For most of my projects the trade-offs above don't materialize. Regarding all the performance and bundle size concerns, I've spoken to Colin, creator of Zod, on a couple of occasions about these and they're all getting addressed in Zod v4 which I'm raring to try out when it's available.
- ashu1461 2y agoI think static type inference can be a big win, considering that the typescript type is already a contract and defining the contract again for validation libraries (joi / zod) feels like an overkill.
- euclideansphere 2y agoCan someone explain to me why I would need something like this over just hand rolling my own validation? Almost every time I've seen one of these JS validation libraries used, it was to verify a form with < 10 inputs and every one of those validations were no more complex than `isNonEmptyString = (x: string | undefined) => x != null && x.trim() != "")` or `isGtZero = (x: any): !isNaN(parseInt(x, 10)) && parseInt(x, 10) > 0` This feels about as trivial as an aggregate package of `isOdd` / `isArray` absurd micropackages. Surely I must be missing something because they're incredibly popular?
- _betty_ 2y agofor me i can auto-gen basic validation from either my typescript or graphql type. Then fairly easily extend it manually. yeah i could do it manually, but the integration with other tools was the killer.