Utility Type Required in TypeScript
Required is a utility type in TypeScript that makes all type properties required if they were optional. When working with objects where some fields may not always be filled, Required ensures strict requirement of all properties at a certain development stage or in a certain context.
Syntax
Required<T>
T— original type whose properties you want to make required.
The Required type turns each property of T into required, removing the question mark ?. This is especially useful when after validation or additional data processing you're sure objects should contain all fields.
When to use Required?
- If you need to guarantee object has all properties.
- When forced to fill optional fields before sending data.
- In functions requiring complete object without undefined.
Required Usage Examples
Converting optional properties to required:
Suppose we have a User interface with several fields, some of which may be missing:
interface User {
id: number;
name: string;
age?: number;
address?: string;
}
type RequiredUser = Required<User>;
const user: RequiredUser = {
id: 1,
name: "Alice",
age: 30,
address: "Wonderland Ave",
};
Useris the original interface where age and address fields may not be set.RequiredUserturns all fields (including age and address) into required.- When attempting to skip any of the age or address properties, TypeScript will throw an error requiring their mandatory specification.
Using Required for post-validation:
Often you first describe data as Partial<User> (or with optional fields), collecting them in parts, then after validation want to get a "full" version of the type where fields are guaranteed to exist:
function createUserData(data: Partial<User>): Required<User> {
// ... Perform validation and fill missing fields
return {
id: data.id ?? 0,
name: data.name ?? "Unknown",
age: data.age ?? 0,
address: data.address ?? "Unknown",
};
}
const partialUser: Partial<User> = { name: "Bob" };
const fullUser: Required<User> = createUserData(partialUser);
// fullUser has all required fields (id, name, age, address)
In this situation after performing checks and filling values, the function returns an object of type Required<User> where all fields are now required.