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. 🎉

TypeScriptTs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.