TypeScript Course
TypeScript
/
Intermediate

Omit<T, Keys>

Definition

A utility type that constructs a new type by starting with an existing type (`T`) and removing a specific set of properties (`Keys`).

Explain Like I'm New

The opposite of `Pick`. If a buffet has 50 dishes, `Pick` is naming the 2 dishes you want. `Omit` is telling the chef: 'Give me literally everything on the table EXCEPT the tomatoes and onions.'

Real World Example

Creating a type for a 'Create User' form payload. The database `User` type has an `id` and `createdAt` date. The user cannot submit these; the database generates them. So the payload type is `Omit<User, 'id' | 'createdAt'>`.

Common Use Cases

  • •Form payload typing (removing DB-generated fields)
  • •Removing sensitive data (passwords) from types

Interactive Example

interface UserRecord {
  id: string;
  name: string;
  email: string;
  passwordHash: string;
  createdAt: number;
}

// When returning the user to the frontend, NEVER send the password.
type PublicUser = Omit<UserRecord, "passwordHash">;

const safeUser: PublicUser = {
  id: "user_123",
  name: "Alice",
  email: "a@a.com",
  createdAt: 162000000
  // passwordHash is completely stripped from the type requirement
};

Interview Questions

basic

  • When should you use `Omit` instead of `Pick`?

intermediate

  • Does `Omit` throw an error if you omit a key that doesn't exist?

Flash Cards

Question

When to use Omit vs Pick?

Click to reveal answer
Answer

Use `Pick` when the number of properties you want is small. Use `Omit` when the original type has a massive amount of properties, and you only want to remove one or two.

Question

Does it error if the key doesn't exist?

Click to reveal answer
Answer

Historically, NO! Unlike `Pick`, `Omit` was built using `Exclude`, which meant you could omit `'fakeKey'` silently without TS complaining. However, newer versions of TS have improved this behavior in certain strict environments.