Last active
November 4, 2025 21:01
-
-
Save JMassey1/823b5ba3327eb280caa460f74697c903 to your computer and use it in GitHub Desktop.
Zod type for a form value that starts as null but will not accept null
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Borrowed from: github.com/TanStack/form/issues/1583#issuecomment-3127845132 | |
| /** | |
| * Modifies the provided schema to be nullable on input, but non-nullable on output. | |
| */ | |
| function nullableInput<TSchema extends ZodType>(schema: TSchema) { | |
| return schema.nullable().transform((value, ctx) => { | |
| if (value === null) { | |
| ctx.addIssue({ | |
| code: 'invalid_type', | |
| expected: schema._zod.def.type, | |
| input: null, | |
| }); | |
| return z.NEVER; | |
| } | |
| return value; | |
| }); | |
| } | |
| // Usage | |
| const mySchema = z.object({ | |
| selection: nullableInput(z.string()) | |
| }) | |
| type SchemaInput = z.input<typeof mySchema>; | |
| // ^? { selection: string | null } | |
| type SchemaOutput = z.output<typeof mySchema>; | |
| // ^? { selection: string } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment