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