Thanks to visit codestin.com
Credit goes to github.com

Skip to content

toZod (v3.0.0) does not infer nullable+optional (nullish) number type properly #19

@waful

Description

@waful

In my source interface I have:

interface ContrivedInterface {
  problematicNumber?: number | null;
}

I would write it in zod as follows:

const contrivedZod: toZod<ContrivedInterface> = z.object({
  problematicNumber: z.number().nullable().optional()
})

Problem is, the type of problematicNumber from z.infer is z.ZodOptional<z.ZodNullable<z.ZodNumber>>, whereas the type of problematicNumber generated by toZod<ContrivedInterface> is ZodOptional<never> | ZodOptional<ZodNumber> causing a type mismatch.

The exact ts error:

Type '{ problematicNumber: z.ZodOptional<z.ZodNullable<z.ZodNumber>>; }' is not assignable to type '{ problematicNumber: ZodOptional<never> | ZodOptional<ZodNumber>; }'.

My usecase is, I want to be able to send null from client to server as an indicator that I want problematicNumber to be unset on backend because undefined is not a valid JSON value so I can't use it in my payload. So undefined represents a lack of value whereas null represents intentional removal of value.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions