zod icon indicating copy to clipboard operation
zod copied to clipboard

Extending z with custom types

Open anthonyma94 opened this issue 3 years ago • 3 comments

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()?

anthonyma94 avatar Jul 13 '22 13:07 anthonyma94

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.

anthonyma94 avatar Jul 13 '22 16:07 anthonyma94

I'm using dayjs, too. It will be nice if we can extend z with dayjs, moment or other custom types

tiavina-mika avatar Jul 27 '22 16:07 tiavina-mika

#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.

plehnen avatar Aug 02 '22 10:08 plehnen

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.

stale[bot] avatar Oct 01 '22 22:10 stale[bot]

this is a valid issue

stunaz avatar Jan 06 '23 16:01 stunaz

Hi guys,

I am still wondering how to add dayjs type with zod. Any update to deal with this use case ?

Thanks

Yolo390 avatar Aug 11 '23 10:08 Yolo390

I ended up using:

{
  myDayjsProp: z
    .string()
    .transform(v => (v.length && dayjs(v)) || undefined)
    .optional()
}

plehnen avatar Aug 11 '23 11:08 plehnen

I ended up using:

{
  myDayjsProp: z
    .string()
    .transform(v => (v.length && dayjs(v)) || undefined)
    .optional()
}

Thanks for the workaround !

Yolo390 avatar Aug 11 '23 11:08 Yolo390

It will be nice to extend with custom types like moment or dayjs "natively".

Something like this: z.daysjs()

Yolo390 avatar Aug 11 '23 11:08 Yolo390