zod
zod copied to clipboard
Extending z with custom types
I'm using Day.js extensively in my application. The way to check for dayjs type is to check instanceof dayjs (the function):
import dayjs from "dayjs";
const date = dayjs();
console.log(date instanceof dayjs) // true
The param type of z.instanceof only accepts classes with constructors, but it works in runtime for checking instanceof dayjs. This means that I have to typecast dayjs as any every time I need it in instanceof:
const dateType = z.instanceof(dayjs as any);
Is there an option to extend z so that I can do something like z.dayjs()?
So dayjs actually provides a class for me to use: z.instanceof(dayjs.Dayjs). However, I would still like to know if it's possible to extend z with custom types.
I'm using dayjs, too. It will be nice if we can extend z with dayjs, moment or other custom types
#metoo.
I am using it inside z.preprocess(v => typeof v === 'string' && v.length && dayjs(v), z.instanceof(dayjs.Dayjs)).
z.instanceof(dayjs.Dayjs) is not working. it throws "TypeError: Cannot read properties of undefined (reading 'name') at Object.instanceOfType [as instanceof]"
z.instanceof(dayjs as any) is not working. It turns the type to "any".
but z.string().min(1).transform(dayjs) (instead of preprocess) seems to work.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
this is a valid issue
Hi guys,
I am still wondering how to add dayjs type with zod. Any update to deal with this use case ?
Thanks
I ended up using:
{
myDayjsProp: z
.string()
.transform(v => (v.length && dayjs(v)) || undefined)
.optional()
}
I ended up using:
{ myDayjsProp: z .string() .transform(v => (v.length && dayjs(v)) || undefined) .optional() }
Thanks for the workaround !
It will be nice to extend with custom types like moment or dayjs "natively".
Something like this: z.daysjs()