Z
Zod•7mo ago
Yamereee

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
const ApiResponseSchema = z.object({
files: z.array(
z.object({
LastModified: z.coerce.date(),
}),
),
});

export type ApiResponse = z.infer<typeof ApiResponseSchema>;
const ApiResponseSchema = z.object({
files: z.array(
z.object({
LastModified: z.coerce.date(),
}),
),
});

export type ApiResponse = z.infer<typeof ApiResponseSchema>;
In my test
const mockResponse: ApiResponse = {
files: [
{
LastModified: '2023-10-10T10:12:41.000Z' as unknown as Date, // I need to cast to date
},
{
LastModified: '2023-10-18T10:12:41.000Z' as unknown as Date, // Even though the API returns strings first
},
{
LastModified: '2023-10-20T10:12:41.000Z' as unknown as Date, // Which is then converted by zod
},
],
};
const mockResponse: ApiResponse = {
files: [
{
LastModified: '2023-10-10T10:12:41.000Z' as unknown as Date, // I need to cast to date
},
{
LastModified: '2023-10-18T10:12:41.000Z' as unknown as Date, // Even though the API returns strings first
},
{
LastModified: '2023-10-20T10:12:41.000Z' as unknown as Date, // Which is then converted by zod
},
],
};
How can I type my mock response so I don't need to cast unknown and then to date?
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)
Jump to solution
4 Replies
Scott Trinh
Scott Trinh•7mo ago
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
Scott Trinh
Scott Trinh•7mo ago
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)
Scott Trinh
Scott Trinh•7mo ago
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.
Yamereee
Yamereee•7mo ago
Thanks! using z.input along with the transform helped