Required for Validation Results
What you'll learn: How to use Required<T> to transform validated or initialized objects from optional to fully populated types.
The Validation Problem
When you validate user input or external data, you often start with a type that has optional properties (reflecting uncertainty about what you'll receive). After validation succeeds, you know all fields are present—but TypeScript doesn't automatically understand this shift.
Required<T> lets you express this knowledge at the type level, converting all optional properties to required ones.
The Pattern
Imagine a form validation scenario:
type UserForm = {
username?: string;
email?: string;
age?: number;
};
function validateForm(input: UserForm): Required<UserForm> | null {
if (!input.username || !input.email || !input.age) {
return null;
}
// Now we know ALL fields exist
return input as Required<UserForm>;
}
const result = validateForm({ username: "alice", email: "a@b.com", age: 30 });
if (result) {
// TypeScript knows these are all present, no undefined checks needed
console.log(result.username.toUpperCase());
console.log(result.email.length);
}
When This Matters
This pattern shines when:
- Validating API responses before use
- Initializing configuration objects with defaults
- Converting partial user input into complete entities
- Ensuring database records have all required fields after hydration
Key Takeaway: Use Required<T> to communicate that validation or initialization logic has ensured all optional properties are now present, preventing downstream undefined checks and making your guarantees type-safe.