Welcome back! I am Mihir, and in this lesson we will learn the Omit utility type in TypeScript.
Omit<T, K> creates a new type by removing specific properties from another type.
Basic Omit Example
type User = {
id: number;
name: string;
email: string;
password: string;
};
type SafeUser = Omit<User, "password">;SafeUser behaves like:
type SafeUser = {
id: number;
name: string;
email: string;
};Using Omit
const user: SafeUser = {
id: 1,
name: "Mihir",
email: "mihir@example.com",
};Invalid:
const user: SafeUser = {
id: 1,
name: "Mihir",
email: "mihir@example.com",
password: "secret",
};password was omitted.
Omit Multiple Properties
type CreateUserInput = Omit<User, "id" | "password">;This can be useful when the database creates the id, and the password is handled separately.
Omit vs Pick
Use Pick when you want only a few fields.
type PublicUser = Pick<User, "id" | "name">;Use Omit when you want most fields except a few.
type SafeUser = Omit<User, "password">;Useful for Component Props
type ButtonProps = {
label: string;
onClick: () => void;
internalId: string;
};
type PublicButtonProps = Omit<ButtonProps, "internalId">;The public type hides implementation details.
Quick Recap
Omit<T, K>removes properties from a type.- It is useful when you want most fields except a few.
- You can omit multiple properties with a union.
- It is commonly used for API inputs and public object shapes.
Pickselects fields;Omitremoves fields.
Next up, we will learn Record →.