Omitting Values from Types in TypeScript

In this short article, we will explore how to omit specific properties from a type using TypeScript's Omit utility type.

"Omitting Values from Types" with a TypeScript logo

The Omit utility type in TypeScript allows you to create a new type with a subset of properties from an existing type by excluding specified properties.

The Omit type is used as follows:

// Declare our type
interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}

// Create a new type using Omit and an existing type. 
type UserWithoutPassword = Omit<User, 'password'>;

// Equivalent to:
// type UserWithoutPassword = {
//   id: number;
//   name: string;
//   email: string;
// }

We can also Omit multiple keys by passing a union od string literals:

// Declare our type
interface User {
 id: number;
 name: string;
 email: string;
 password: string;
}

// Create a new type using Omit and an existing type. 
type UserWithoutPassword = Omit<User, 'password' | 'email'>;

// Equivalent to:
// type UserWithoutPasswordOrEmail = {
//   id: number;
//   name: string;
// }

For further reading, you can check out the docs here.


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

TypeScriptJavaScriptWeb Development
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.