Skip to content

Instantly share code, notes, and snippets.

@JMassey1
Last active November 4, 2025 21:01
Show Gist options
  • Select an option

  • Save JMassey1/823b5ba3327eb280caa460f74697c903 to your computer and use it in GitHub Desktop.

Select an option

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
// 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