What is Required Utility Type in TypeScript?
The Required utility type is the opposite of Partial. It makes all optional properties in a type to be required.
In a simple way, allows you to create a new type that makes all properties of the original type required.
Syntax:
type Required<Type> = {
[Property in keyof Type]-?: Type[Property];
};
To understand the syntax here’s the further illustration:
- Type represents your original type or interface.
- The -? modifier ensures that all properties become mandatory in the new type.
Example:
interface Employee {
id?: number;
name: string;
age?: number;
}
const employee: Required<Employee> = {
id: 10101,
name: "Code",
age: 18
};
The Required utility type does indeed make all optional properties in a type mandatory. It’s especially useful in scenarios where all fields are required, such as user registration.
In our example, the Employee interface has optional properties id and age.
When we use Required<Employee>, all properties become required.
So, the employee object must have all three properties: id, name, and age.
How to use Required Utility Type in TypeScript?
Here’s the step-by-step guide on how to use the Required utility type in TypeScript:
Step 1: Define Your Original Interface or Type
First, you have to create an interface or type that represents your object with optional properties.
For example:
interface Student{
name?: string;
age?: number;
}
Step 2: Use the Required Utility Type
Next step, you have to apply the Required utility type to your original type.
type RequiredStudent = Required<Student>;
After defining your original type and applying the Required utility type to create a new type where all properties are required.
This implies that every property of RequiredStudent is now required.
Here’s how you can do it:
interface Student {
name?: string;
age?: number;
}
const student: Required<Student> = {
name: 'Code',
age: 18,
};
const invalidStudent: Required<Student> = {
name: 'Code', // This is invalid because age is missing
};
As you can see, the student object enforces that both name and age properties must be present.
However, the invalidStudent object is indeed invalid because it lacks the required age property.
Step 3: Handling Errors
If you try to omit a required property, TypeScript will raise an error indicating that it’s required.
And that’s it! You’ve successfully used the Required utility type to ensure your object properties are complete.
Conclusion
So there you have it, we’re done learning the TypeScript Required, which allows you to create a new type that makes all properties of the original type required.
When you apply Required to a type, it ensures that every property defined in that type must be present in any instance of the new type.
I hope this article has given you some insights and helped you understand the TypeScript Required.
If you have any questions or inquiries, please don’t hesitate to leave a comment below.