Skip to content

formMeta is initially undefined, but its type is missing an undefined union #1774

@napewnoarnold

Description

@napewnoarnold

Describe the bug

Doing this in React will crash your app without a typescript error in development:

const form = useForm({ defaultValues: { name: '' } });
console.log(form.state.fieldMeta.name.isValid);

This happens because during first render, the value of form.state.fieldMeta is an empty object, but its type is Record<DeepKeys<TData>, AnyFieldMeta> so when accessing with a valid key the type will be AnyFieldMeta allowing for unchecked access (regardless of tsconfig.json configuration).

Your minimal, reproducible example

https://stackblitz.com/edit/tanstack-form-an6ruffx?file=src%2Findex.tsx

Steps to reproduce

  1. Go to the stack blitz example
  2. Observe how typescript reports no errors in src/example-minimal.tsx
  3. Observe how the try catch block caught an error

Expected behavior

Either

Make fieldMeta a Record<DeepKeys<TData>, AnyFieldMeta | undefined>, so that accessing anything on fieldMeta has to be optionally chained

or

Provide values during first render (assuming that's a bug?)

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

All of them

TanStack Form adapter

react-form

TanStack Form version

1.23.4

TypeScript version

^5

Additional context

I've included a real world example where this becomes a problem in stack blitz src/example-real-world.tsx

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions