Yamereee - 👋 Hello Zod Wizards! A Question wh...
👋 Hello Zod Wizards! A Question when using coerce with my API responses, I have a schema here
Note that LastModified is a
string
but is an ISO date string
In my test
How can I type my mock response so I don't need to cast unknown and then to date?Solution:Jump to solution
If you want better type information, you can use
z.string().transform((dateString) => new Date(dateString))
especially if you know the input is and should be a string rather than something else coercible to a date (like number
for instance)4 Replies
you can use
z.input
instead of infer here, but it'll give you the same result. coerce
just throws away the type information of the input which is one of it's drawbacks.Solution
If you want better type information, you can use
z.string().transform((dateString) => new Date(dateString))
especially if you know the input is and should be a string rather than something else coercible to a date (like number
for instance)On the other hand, if you want the data to be polymorphic (accepts strings, numbers, existing
Date
objects, etc), then the cast that you're doing in your mock response is appropriate.Thanks! using z.input along with the transform helped