Blog>
Snippets

Avoiding Common Mistakes in Typed Form Development

Compare examples of common mistakes made when developing forms with TypeScript and TanStack Form, such as overcomplicating types or misusing validation schemas, against best practice solutions.
// Mistake: Overcomplicating types 
const formValues: { name?: string; age?: number } = {};
useForm({ defaultValues: formValues });
This example shows an overcomplicated type definition where all properties are optional, which may not accurately enforce the form's requirements.
// Best practice: Simplify types by making them explicit 
interface FormValues {
  name: string;
  age: number;
}
const formValues: FormValues = { name: '', age: 0 };
useForm({ defaultValues: formValues });
This example simplifies type definitions by explicitly defining the shape of the form's data, making it clearer and avoiding unnecessary optionals.
// Mistake: Misusing validation schemas 
const formOptions = {
  validate: values => {
    const errors = {};
    if (!values.name) errors.name = 'Name is required';
    return errors;
  }
};
useForm(formOptions);
This example depicts a mistake where validation is handled inside the form options in an untyped and potentially inconsistent manner.
// Best practice: Use validation schema for consistency and type safety 
import * as Yup from 'yup';

const validationSchema = Yup.object({
  name: Yup.string().required('Name is required'),
  age: Yup.number().min(1, 'Age must be greater than 0').required('Age is required')
});

const formOptions = { validationSchema };
useForm(formOptions);
This example utilizes Yup to define a validation schema, improving consistency across the form and leveraging type safety for validations.