TypeScript Required Utility Type
In this article, we'll dive deep into a useful but something I rarely see used utility type - Required<Type>
.
The Required
utility type lets you enforce that all properties are "required" from an existing type and create a new one.
Required in Action
In the Required<Type>
syntax, Type
is the original type.
This is easier with an example. Given this User
type with all optional properties:
interface User { id: number?; name: string?; email: string?; age: number?; }
Now assume we want to make all the fields required, Required
makes our life easier.
const invalidRequiredUser: Required<User> = { name: 'Niall Maher', email: 'niall.maher@codu.co' }; // ❌ This will throw a compile-time error as all properties are required in Required<User>
The above will error as we have not passed all of the values in User
. Now let's look at a valid example:
const requiredUser: Required<User> = { id: 123, name: 'Niall Maher', email: 'niall.maher@codu.co', age: 32`` }; /* Required<User> behaves as if we typed the following: interface User { id: number; name: string; email: string; age: number; } */
In this scenario, requiredUser
has a new type that enforces all fields as required.
This concept might seem trivial, but when working on large-scale applications with complex data structures, such precise control over your types becomes a game-changer
Follow me on Twitter or connect on LinkedIn.
🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉