TypeScript Partial Utility Type
In this article, we'll dive deep into a useful and frequently used utility type - Partial<T>
.
Partial<T>
is a utility type that creates a new type, making all properties of the input type T
optional.
This utility becomes extremely useful in situations like updating or modifying an existing data object.
Partial in Action
I think it'll make more sense when you see it in action:
interface User { id: number; name: string; email: string; age: number; } const partialUser: Partial<User> = { email: 'test@cod.co' }; /* Partial<User> behaves as if we typed the following (making all the User elements optional): interface User { id?: number; name?: string; email?: string; age?: number; } */
When we declare partialUser
as Partial<User>
, we're saying that this object can have any combination of User's fields, including having none of them at all.
So as an example, { name: 'Sir bottom' }
, { id: 2, email: 'test@codu.co' }
, or even {}
would all be valid values for partialUser
.
Now hopefully, that's a new trick for you to introduce into your workflows to stop duplicating types.
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. 🎉