Typescript is a powerful language that allows you to create complex data structures and types. It's used to create types that are more specific than just any
. Two particularly useful features are TypeScript Omit
and Pick
, which help us create more precise types by either excluding or including specific properties. This helps us catch errors at compile time and make our code more robust.
When working with TypeScript types, you'll often encounter scenarios where you need to create new types based on existing ones. TypeScript provides two powerful utility types for this purpose: Omit
helps you create types by excluding specific properties, while Pick
lets you build types by selecting only the properties you need. Let's explore these utilities and see how they can improve your TypeScript code.
What is Typescript Omit?
The Omit
utility is a TypeScript type that allows you to create a new type by excluding one or more properties from an existing type. It's a powerful tool for working with complex data structures and ensuring that your code is as clean and readable as possible.
Omit<Type, Keys>
creates a new type by picking all properties from Type
except those specified in Keys
. Think of it as a "property eraser" for types.
How to Use Typescript Omit
To use Omit
, you need to import it from the @type
package. Here's an example:
interface User {
id: number;
username: string;
password: string;
email: string;
}
// Create a public user type without sensitive info
type PublicUser = Omit<User, "password">;
const user: PublicUser = {
id: 1,
username: "codewizard",
email: "wizard@code.com"
// No password property! ✨
};
In this example, PublicUser
is a new type that includes all properties from User
except password
. This type of definition helps us protect sensitive information from being exposed among other things.
Few places where Omit might be useful
API-Response Cleaning
When you're working with an API, you often need to clean up the response to remove any sensitive information. Omit can help you do this by excluding properties that you don't want to expose and can help you clean the data before sending it to the client:
interface DatabaseUser {
id: number;
username: string;
password: string;
passwordSalt: string;
email: string;
lastLogin: Date;
}
// Remove sensitive fields for client-side use
type ClientUser = Omit<DatabaseUser, "password" | "passwordSalt">;
function sanitizeUser(user: DatabaseUser): ClientUser {
// TypeScript ensures we don't include sensitive fields
const { password, passwordSalt, ...clientUser } = user;
return clientUser;
}
Here, we're creating a ClientUser
type that excludes the password
and passwordSalt
properties from the DatabaseUser
type. This helps us clean the data before sending it to the client.
Form Validation
When you're creating forms, you often need to exclude certain properties from the form data. Omit can help you do this by excluding properties that you don't want to include in the form.
interface ProductForm {
name: string;
price: number;
createdAt: Date;
updatedAt: Date;
computedTax: number;
}
// Only include editable fields
type EditableProductFields = Omit<ProductForm, "createdAt" | "updatedAt" | "computedTax">;
function updateProduct(id: number, updates: EditableProductFields) {
// Only allows updating name and price
// ...
}
Simplifying Derived Types
Omit can also be used to simplify derived types. For example, if you have a type that includes a lot of properties, but you only need a subset of them, you can use Omit to create a new type that includes only the properties you need:
type User = {
id: number;
username: string;
password: string;
email: string;
createdAt: Date;
updatedAt: Date;
};
// Create a simplified type without unnecessary properties
type UserWithoutPassword = Omit<User, "password" | "createdAt" | "updatedAt">;
In this example, UserWithoutPassword
is a new type that excludes the password
, createdAt
, and updatedAt
properties from the User
type. This helps us simplify the type and make it easier to use.
What is Typescript Pick?
Pick is a TypeScript utility that allows you to pick specific properties from a type. It's similar to Omit, but instead of excluding properties, it includes only the properties specified in the second argument.
Pick<Type, Keys>
creates a new type by picking the properties specified in Keys
from Type
.
How to Use Pick
To use Pick, you need to import it from the @type
package. Here's an example:
interface User {
id: number;
username: string;
password: string;
email: string;
}
// Create a new type with only the specified properties
type UserWithEmail = Pick<User, "email">;
In this example, UserWithEmail
is a new type that includes only the email
property from the User
type. This is useful when you only need a subset of the properties from a type.
Comparison between Omit and Pick
Feature | Omit | Pick |
---|---|---|
Purpose | Excludes specified properties from a type | Includes only specified properties from a type |
Syntax | Omit<Type, Keys> |
Pick<Type, Keys> |
Result | Creates type with all properties except those specified | Creates type with only the specified properties |
Use Case | When you want to remove specific properties | When you want to keep specific properties |
Property Selection | Define properties to exclude | Define properties to include |
Type Safety | Maintains type safety of remaining properties | Maintains type safety of selected properties |
Conclusion
In this article, we saw how to use TypeScript Omit
and Pick
to create new types by excluding or including specific properties from an existing type. We also explored some practical use cases for these utilities.
By understanding how to use Omit
and Pick
, you can create more flexible and robust types in your TypeScript code.
I hope this article was helpful and you learned something new. To learn more about TypeScript Omit
and Pick
and a few more utility types, you can check out the TypeScript documentation.
Happy coding!
Top comments (1)
Great article. Thanks for sharing!