TypeScript Omit Utility Type
In this article, we'll dive deep into a useful and frequently used utility type - Omit<Type, Keys>
.
As the name implies, the Omit
utility type lets you "omit" properties from an existing type and create a new one.
Omit in Action
In the Omit<Type, Keys>
syntax, Type
is the original type, and Keys
is the set of properties that should be omitted from Type
.
This is easier with an example. Given this User
type:
interface User { id: number; name: string; email: string; age: number; }
Now assume we only want to deal with the name
and email
fields. Here is where Omit
makes our life easier:
const omitUser: Omit<User, 'id' | 'age'> = { name: 'Niall Maher', email: 'niall.maher@codu.co' }; /* Omit<User, 'name' | 'email'> behaves as if we typed the following: interface User { name: string; email: string; } */
In this scenario, omitUser
has a new type that only includes the name
and email
properties from User
.
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. 🎉