TanStackT
TanStack6mo ago
3 replies
urgent-maroon

TanStack Form + Zod: Type error with enum default values in onChange validator

Having a TypeScript issue with TanStack Form + Zod schema validation. Getting a type error when using my schema in the
onChange
validator.

Schema:

export const beverageSchema = z.enum(['coffee', 'tea', 'water']).default('water')

export const peopleSchema = z.object({
  fullName: z.string().min(1, 'Full name is required'),
  email: z.string().optional(),
  phone: z.string().min(1, 'Phone is required'),
  address: addressSchema,
  beverage: beverageSchema, // Has default but not optional
})

export const peopleFormOpts = formOptions({
  defaultValues: {} as PeopleFormData, // Empty defaults
})


Form usage:

const form = useAppForm({
  ...peopleFormOpts,
  validators: {
    onChange: peopleSchema, // ❌ Type error here
  },
  onSubmit: ({ value }) => {
    alert(JSON.stringify(value, null, 2))
  },
})


Type error:
The types of 'input.beverage' are incompatible between these types.
Type '"coffee" | "tea" | "water" | undefined' is not assignable to type '"coffee" | "tea" | "water"'.
Type 'undefined' is not assignable to type '"coffee" | "tea" | "water"'.


What I need:

1. Use Zod schema directly in onChange validator (no manual parsing) - so I can have field level errors
2. Keep typed default values for child forms

The beverage field has a default value but isn't optional - should TanStack Form handle this automatically? How can I resolve this type mismatch while maintaining the schema structure? Here is a reproduction repo: https://github.com/snigdha920/tanstack-zod/tree/main
GitHub
Contribute to snigdha920/tanstack-zod development by creating an account on GitHub.
GitHub - snigdha920/tanstack-zod
Was this page helpful?