Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
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.
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.
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",
};
User is the original interface where age and address fields may not be set.RequiredUser turns all fields (including age and address) into required.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.