Describe the bug#
Sometimes forms may have optional fields that don't have to be defined every time, but they can be later be set/unset by users. The default values of a form may only contain a subset of the available fields.
It's also the same problem with custom form hooks...
TanStack form doesn't work properly with subschemas in Zod marked with optional():
- It leads to a TS error in
validators.onChange (see CodeSandbox)
- We cannot access fields that aren't given default values... It's simply missing from the options listed in
name prop of form.Field
I suggest lift up some restrictions and not force all values to be defined in defaultValues. Maybe we should have the ability to grant a generic TFormData or a resolver like react-hook-form... or a pass() or skip() utils that we will assign to the optional values inside the defaultValues to make them recognized by TanStack form, but they aren't actually assigned...
Your minimal, reproducible example#
https://codesandbox.io/p/devbox/6v2kfr
Steps to reproduce#
- Go to the CodeSandbox
- Try to refer to one of the optional fields (for example in the
name prop or form.Subscribe selector={(state) => [state.values.log_sinks.file.encryptionSalt]})
- Won't work because TanStack Form doesn't recognize these values because they weren't given default values (they shouldn't got one in first place!)
Expected behavior#
I expected optional values that were missing to be still recognized by TanStack Form, and also not receive TS error from validators.onChange
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
TanStack Form adapter#
react-form
TanStack Form version#
v1.12.2
TypeScript version#
v5.8.3
Additional context#
No response
You did not inform TypeScript about your intentions, that being that
defaultValuesshould be inferred asz.input<typeof ConfigSchema>.TypeScript instead inferred your default values as they are defined, which is
It usually catches mistakes like these, if it weren't for a feature that zod has:
Zod does not differentiate between optional properties and unions with undefined.#
These are equivalent in Zod. Type B cannot be created from schemas:
While TypeScript does differentiate these two. You must initialize the latter as undefined. Because Zod typed it as
A, your defaultValues match the criteria even though you did not initialize optional values.To fix this, inform TypeScript about your intentions: