Thanks Matt! Incredible as always! Florian mentioned a couple uses cases for z.symbol() below. I've also not used it much personally, but it always irked me as an inconsistency between Zod and TS. Symbols are one of three kinds of primitive values that can be used as keys in JS objects so it was particularly odd that Zod didn't represent them in any way: type anyKey = keyof any; // string | number | symbol Though `z.object` doesn't actually support them yet as keys...something for a future release! const matt = Symbol("mattpocock"); const schema = z.object({ [matt]: z.string().catch("cool dude"), });
@jon18672 жыл бұрын
These are friggin awesome changes. The functional programmer deep inside of me feels satisfied. I honestly don't know which one to be the most hyped for.
@krome3052 жыл бұрын
always good to hear new updates from matt channel
@irlshrek2 жыл бұрын
One of my favorites libraries is ts-pattern. Worth a look!
@EduardoLarios95 Жыл бұрын
Love that lib, I've always loved pattern matching and it really feels natural in TS.
@MachineYearning2 жыл бұрын
I'm not a huge fan of zod doing things like transforming the data with fallbacks etc. To me it's a validation library, which gives me a clear mental model about what it does and what it returns (tells me if the data is valid or not). I feel like adding bells and whistles on for "convenience features" has a way of gradually polluting very simple concept libraries into grab-bag hodge podge frameworks. Hope they can keep it under control because zod is one of my favorite libraries
@dealloc2 жыл бұрын
You don't have to use it, if you don't find it useful. But I like it because it means that you can more easily reuse schemas without needing to manually parse and check each value every time, especially considering that you now also have "pipe".
@MachineYearning2 жыл бұрын
@@dealloc The pipe() feature is fine, I'm talking about the default() function and other things that transform the returned data during parsing.
@dealloc2 жыл бұрын
@@MachineYearning I know, and that was the first thing I talked about :) But the type makes more sense with pipe also for easy reusability.
@MachineYearning2 жыл бұрын
@@dealloc My misunderstanding. Anyway the thing about "if you don't like it, don't use it" is that no one really codes in a vacuum. You are bound to either inherit some code, or have someone touching code you wrote, trying to use one of these features. Not to mention that people will be wondering what other kinds of data transformation zod can do during parsing/validation now, and requesting the next "convenience" feature. At some point you have to balance whether the library itself has the responsibility to support however people wanna use it, or to keep a clean and principled layer of abstraction.
@dealloc2 жыл бұрын
@@MachineYearning In this case it doesn't really matter, because if you're consuming a schema from a third-party source, you already decided to adhere to said schema-that's what schemas are for. In case you use a library that adds validation, you shouldn't have to care what method they use for validating your input. The rest is implementation details and would otherwise be a leaky abstraction, if they exposed these details in their API.
@FlorianWendelborn2 жыл бұрын
5:00 I’ve used Symbols in zod for some shared form prop validation in vue where some fields didn’t support specific props. Due to Vue’s lack of real TS support, it needs to be done at runtime unfortunately, so those props default to Symbol(NEVER) and the runtime validation only passes when that specific symbol is still passed (so, when nothing else is passed to the prop). This ensures devs don’t ever pass props that aren’t supported which is misleading otherwise
@quintencabo2 жыл бұрын
Do you mean vue 2?
@daheck812 жыл бұрын
@@quintencaboYea i think so. Vue has excellent TS support since v3
@FlorianWendelborn2 жыл бұрын
@@quintencabo I mostly mean vue 2, but with @vue/composition-api. However, this also isn’t entirely fixed in vue 3 for props. .vue files unfortunately will always be a hassle due to not being a standard like .tsx. But yes, vue3 is significantly better than vue2 for TS, and even vue2 with composition-api is already miles ahead of vue2.
@FlorianWendelborn2 жыл бұрын
@@daheck81 Unfortunately TS support for the template itself (including component props, which is what I’m talking about here) is still lacking. I still think the decision to invent a new file format and templating language is one of the worst choices vue made since it means that stuff like TS support is NOT out-of-the-box like it would be with JSX and styles via tagged template literals etc..
@daheck812 жыл бұрын
@@FlorianWendelborn You can define props as interfaces in vue 3. You might want to check out the "script setup" declaration. The only thing i currently miss is being able to import types from other files and use them to declare the props, this will be added in vue 3.3 tho. For the templating part vue relies on volar (which is an overhead, i agree). But as a type nerd I am overall satisfied with its current state
@modernkennnern2 жыл бұрын
I started using Zod for the first time literally this weekend, and one of the things I wanted to do was parse a stringified `DateOnly`(C#) value ("2022-12-15"), and I was surprised to found out I had to do it manually. Good to see it's now been implemented (Albeit seemingly requiring some semi-arbitrary precision option?)
@ColinMcDonnellCorner2 жыл бұрын
This still isn't implemented actually, only full ISO datestring validation, which is complex enough that I figured it merited a dedicated API. For things like date strings, I refer people to the `.regex()` method, which can be used in conjunction with a library like validator.js that exposes a ton of common validations (more than would be feasible to expose in Zod's relatively minimal API)
@JacksonMarshal2 жыл бұрын
Thanks, Matt, for the amazing video. I didn't know about transform function.
@ulterior_web2 жыл бұрын
The lack of composability was my biggest annoyance vs io-ts - glad to see the pipe function!
@FlorianWendelborn2 жыл бұрын
2:15 I’ve previously used z.preprocess for similar things. I think the pipe example isn’t great since I see no reason to use pipe over preprocess just from the example.
@GordonChil2 жыл бұрын
Zod has one of the coolest logos in open source.
@mattpocockuk2 жыл бұрын
That illustration was actually made for Total TypeScript! I'd love it if they adopted it, though.
@JayFGrissom Жыл бұрын
At 3:00 when you are changing the input to parse() how are you getting those dynamic updates in the test? Video edits? If not this is a tool I need in my toolbox (that I’m missing).😢
@mattpocockuk Жыл бұрын
It's vitest, running with vitest -u to automatically update the snapshots.
@JayFGrissom Жыл бұрын
@@mattpocockuk You are a rockstar. Thank you for sharing this.
@Mitsunee_2 жыл бұрын
I immediatly remembered a usecase for coerce. I have a yaml file with some numeric IDs mapping release dates of something, which is either an Enum (for reuseable dates) or a number. I've had problems where zod saw the keys (my numeric IDs) as string, but I really wanted a Record in the end. Edit: here's my current workaround: z.string().regex(/^\d+$/).transform(val => +val)
@kuldeepbhatt84752 жыл бұрын
The first code is good for setting and checking the length of the password for the use case.
@anhdunghisinh2 жыл бұрын
Wow, this is really cool, i have so many problem working with query param for paging due to query param has to be string but paging needs number, so i have to write a lot of parseint and toString to solve this
@d.sherman8563Ай бұрын
Really liked the video, just one point of feedback. Using inline snapshots to validate the result is a bit confusing because it appears as if everything you parse is a string while it’s not.
@rujor2 жыл бұрын
Hmm, I just keep waiting for an excuse to switch from Joi to Zod (because a lot of people seems to go on about it), but that first example is actually super easy and intuitive in Joi 🤷..
@the-old-channel2 жыл бұрын
Zod is cool, but I prefer superstruct. It’s smaller, faster a had coercion for ages.
2 жыл бұрын
The only thing where symbol would make sense if you would like to validate that an object is iterable (because then it has to support Symbol.iterable key). Maybe there is a use case for that. Date/time support is great. Does this enable transforming from string to date? So if I have const schema = z.object({ value: z.datetime().transform(d=>new Date(d)) }) and I use it will it then return an object where 'value' has been converted from string to javascript Date?
@mattpocockuk2 жыл бұрын
Yes!
@darkdande922 Жыл бұрын
Which one do you suggest to use? Joi or zod? especially for nestjs.
@carlosricardoziegler26502 жыл бұрын
Nice review :) what abou error friendly ? I use Boom but we have some alternative? Thanks
@blankcheckguy692 жыл бұрын
how secure is Zod for validating things like product releases or NFT drops? could it be exploited to trick the ‘z.datetime’ or things like that?
@dealloc2 жыл бұрын
If that is the case, then you should report it as a bug in Zod's issues. Zod is meant for validation of _user_ input. If it provides a built-in mechanism to validate a specific type, you can be sure it is safe (except RegEx, RegEx matching directly on user input should always be considered unsafe). But if you use general validators for things that doesn't have built-in support, you will need to sanitize yourself.
@andrewdunbar8282 жыл бұрын
Have you misspoked? You have indeed misspoked.
@DmitriiBaranov-ib3kf20 күн бұрын
Typebox feels much better
@ilijanl2 жыл бұрын
Wonder what your thoughts are on Typebox, which does similar thing but additionally outputs a valid JSONSchema
@mattpocockuk2 жыл бұрын
I'm in love with Zod, so I'd need a reason to use JSONSchema to consider Typebox I think.
@twitchizle2 жыл бұрын
@@mattpocockuk there is also zod to json schema pkg
@mattpocockuk2 жыл бұрын
@@twitchizle Yes, true!
@ilijanl2 жыл бұрын
Just wondered if you ever have used it and what your thoughts were.
@uziboozy45402 жыл бұрын
@@mattpocockuk have a look at Deepkit.
@kevyyar Жыл бұрын
Where's your course link? Been waiting for more than a year lol
@mattpocockuk Жыл бұрын
Here it is! totaltypescript.com
@AtomicCodeX5 ай бұрын
Thank you for this I chose to use types even though I use c# on the backend But I use types cuz I was like fuck it, I’m not using inheritance 😆
@wlockuz44672 жыл бұрын
How does it compare to yup?
@anatolydyatlov9632 жыл бұрын
I feel like an excellent use case for .coerce will be Mongo ObjectIDs. You often want to convert them to strings with the "toString" method, e.g. when passing them to the frontend, but allow them to be ObjectIDs when they're still handled by the backend, e.g. when you receive them from the database. For now, I have a custom type: export const TObjectId = z.union([z.instanceof(ObjectID), z.string()]).transform((arg, ctx) => { try { if (typeof arg === "string") return arg; if (arg instanceof ObjectID) return arg.toString(); throw new Error(`Wrong _id type: ${typeof arg}`); } catch (error) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: getErrorMessage(error), }); } }); export type TObjectId = z.infer; I think I can convert it to a much simpler .coerce type in 3.20. Unfortunately, I first have to resolve some breaking issues between 3.18 and 3.19, which result in z.pick not working as previously.
@lsagar2 жыл бұрын
Is this an alternative of yup?
@mattpocockuk2 жыл бұрын
Yes, exactly! It's very very good.
@benslv2 жыл бұрын
yup!
@mattpocockuk2 жыл бұрын
@@benslv teehee
@abduraufsherkulov13932 жыл бұрын
@@mattpocockuk It is a shame that it doesn't support i18n
@mattpocockuk2 жыл бұрын
@@abduraufsherkulov1393 You mean for error messages? Interesting.
@chhiethearith95252 жыл бұрын
I think ZOD look like class-validator in NestJs
@GoWokeGoBroke12 жыл бұрын
🎉
@lambgoat24212 жыл бұрын
having coerce would have made a task I had earlier a lot easier
@brennenherbruck87402 жыл бұрын
What's this `vitest` REPL black magic going on here? A vscode extension?
@mattpocockuk2 жыл бұрын
Just running vitest -u in the background!
@AjinkyaBorade Жыл бұрын
Isn’t it similar to YUP
@michaelbitzer72952 жыл бұрын
Not sure why zod does not have a way to abort early. Such a massive dealbreaker for me.
@uziboozy45402 жыл бұрын
Zod isn't near the best TypeScript library. It's like JSON schema. It's pretty shit imho. Anyhow, it's nothing compared to Deepkit.
@ColinRichardson2 жыл бұрын
Only thing I don't like about Zod is it blurs the boundaries from a really advanced and precise asserting library, to a transformation library.. I just wished there is a zod-lite that ONLY deals with testing the value.
@mattpocockuk2 жыл бұрын
That's true!
@a895292942 жыл бұрын
💯
@nowifi4u2 жыл бұрын
Still no z.number().integer(), oof
@vieruuuu2 жыл бұрын
.int() exists
@blankcheckguy692 жыл бұрын
@@vieruuuu So do you know if ‘z.number.int()’ works or do you need to use ‘.pipe’ ?
@vieruuuu2 жыл бұрын
@@blankcheckguy69 you need to use z.number().int(), no need for pipe
@zpz45992 жыл бұрын
typescript-json is better.
@uziboozy45402 жыл бұрын
Deepkit is even better lol
@jon18672 жыл бұрын
that's an interesting approach to the same problem, not sure I like the idea of completely changing typescript just to get better developer ergo-dynamics though. Seems like something that would make C# developers feel a lot more at home, but not necessarily provide a huge amount of value to JS natives.
@ulterior_web2 жыл бұрын
@@jon1867 as one such person, I just looked at those libraries and dislike them for making things too magical. It breaks the mental model of the language, and adds yet another compile step for a use case that works fine in a normal library… no thanks.
@jon1867 Жыл бұрын
@@ulterior_web exactly my thoughts. It is pretty cool though
@vim55k Жыл бұрын
Found your content. At least advanced stuff! Not tutorials:(
@atoz8729 Жыл бұрын
Is there any way to convert class object to zod object ? z.object( class name). Please reply
@ColinRichardson2 жыл бұрын
Bug report.. z.coerce.boolean().parse("false") returns true and not false, because any string other than "" is truthy. I know "why" it does it, but the example in your video tested for "true" which can confuse people.
@mattpocockuk2 жыл бұрын
I would expect it to return false here, I think that's a genuine bug.
@FlorianWendelborn2 жыл бұрын
@@mattpocockuk I don’t think it’s a bug. I think it’s simply isn’t clear what the coercion does. As far as I understand, it literally just applies `Boolean()` or `String()` or `Number()` to the respective value Coding some custom logic that does `Boolean()` but IF it says "false" it’s suddenly false would mean unexpected bugs when people don’t expect anything but `Boolean()`
@mattpocockuk2 жыл бұрын
@@FlorianWendelborn Gotcha, this makes sense. I see what Colin was tilting at now.
@MachineYearning2 жыл бұрын
I'm not a huge fan of zod doing things like transforming the data with fallbacks etc. To me it's a validation library, which gives me a clear mental model about what it does and what it returns (tells me if the data is valid or not). I feel like adding bells and whistles on for "convenience features" has a way of gradually polluting very simple concept libraries into grab-bag hodge podge frameworks. Hope they can keep it under control because zod is one of my favorite libraries