Form Validation States
You'll learn how to model form states (pristine, validating, valid, invalid) so they can never overlap incorrectly.
The Problem: Overlapping States
When building forms, you track multiple pieces of state: whether the form is untouched, currently validating, valid, or invalid. The naive approach uses multiple boolean flags:
type FormState = {
isPristine: boolean;
isValidating: boolean;
isValid: boolean;
errors: string[];
};
This creates impossible combinations: a form could be marked as both isPristine: true and isValid: true, or isValidating: true while also isValid: true. These states should be mutually exclusive, but nothing in the type system prevents these contradictions.
The Solution: Discriminated Unions
Model each distinct state as a separate member of a union:
type FormValidationState =
| { status: 'pristine' }
| { status: 'validating' }
| { status: 'valid' }
| { status: 'invalid'; errors: string[] };
Now the states cannot overlap. A form is in exactly one state at any time. Notice that errors only exists when status is 'invalid'—because errors aren't relevant in other states.
Working with the States
TypeScript narrows the type when you check the discriminant:
function renderForm(state: FormValidationState) {
if (state.status === 'invalid') {
// TypeScript knows state.errors exists here
return state.errors.join(', ');
}
if (state.status === 'validating') {
return 'Checking...';
}
return 'Ready';
}
Why This Matters
This pattern encodes your business logic in types. You can't accidentally check errors when the form is pristine, because TypeScript won't let you access a property that doesn't exist in that state variant.
Key Takeaway: Use discriminated unions to model exclusive states—pristine, validating, valid, and invalid—so impossible state combinations become type errors instead of runtime bugs.