Required numeric field with empty initial value causes type error #5800
Replies: 1 comment
-
|
Hi @kk-analytics! I'm Dosu and I’m helping the zod team. Hey! 👋 I'm a bot trained on Zod's codebase and issues. This is a common type mismatch issue when integrating Zod with form libraries (looks like you're using TanStack Form based on The fix: If you want the field to start as const schema = z.object({
price: z.number().int('Price must be an integer').min(0).max(1000000).optional(),
});Or, if you're working with HTML form inputs that return strings, you might want to use coercion with an explicit input type (as recommended by the maintainer): const schema = z.object({
price: z.coerce.number<string>().int('Price must be an integer').min(0).max(1000000),
});Also, don't manually type your If this answers your question, feel free to close this discussion! To reply, just mention @dosu. How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I want:
price to start empty in the UI
Validation to require a number ≥ 0 before submission
No TypeScript type errors with react-form + Zod
const schema = z.object({ price: z.number().int('Price must be an integer').min(0).max(1000000), });const form = useForm({ defaultValues: { price: undefined }, validators: { onSubmit: schema }, });Type 'ZodObject<{ price: ZodNumber; }, $strip>' is not assignable to type 'FormValidateOrFn<{ price: undefined; }> | undefined'.
Type 'ZodObject<{ price: ZodNumber; }, $strip>' is not assignable to type 'StandardSchemaV1<{ price: undefined; }, unknown>'.
The types of ''~standard'.types' are incompatible between these types.
Type 'Types<{ price: number; }, { price: number; }> | undefined' is not assignable to type 'StandardSchemaV1Types<{ price: undefined; }, unknown> | undefined'.
Type 'Types<{ price: number; }, { price: number; }>' is not assignable to type 'StandardSchemaV1Types<{ price: undefined; }, unknown>'.
The types of 'input.price' are incompatible between these types.
Type 'number' is not assignable to type 'undefined'.
Beta Was this translation helpful? Give feedback.
All reactions