colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Using nullable() or nullish() alone #3669

Open w-ap-admin opened 1 month ago

w-ap-admin commented 1 month ago

For a specific use case involving a custom type with a complex type union, I need to ensure that a key is defined, but its value can sometimes be undefined or null. I attempted to create a dummy type like this:

const myZodObject = z.object({ test: z.nullish() });
// or
const myZodObject = z.object({ test: z.nullable().optional() });

However, in both cases, I encountered an error stating that the functions nullable or nullish do not exist.

I can work around this issue by adding a primitive type as shown below, but this solution isn't entirely satisfactory. I am curious to understand why this occurs. Is it due to a technical constraint, such as TypeScript inference, or is it a bug that can be fixed?

If it is a bug, I am willing to investigate further and potentially open a PR to address it. However, I wanted to ask for clarification before proceeding.

Thank you for your help and for this great library, which has already saved me hundreds of hours of work.

w-ap-admin commented 1 month ago

Nobody could answer ?

ankhzet commented 1 month ago

As far as i can tell, nullable, optional and nullish must be of type, i.e. z.number().nullable(), z.string().nullable() etc. If you don't care about particular type, you probably can use any type: z.any() (without optional or nullish)