# TypeScript: `Pick` vs `Omit`

`Pick` and `Omit` are two sides of the same coin. They are both utility types used to derive a new object type by filtering the keys of an existing type.

## 1. `Pick<Type, Keys>` (The Whitelist)

`Pick` constructs a type by selecting a specific set of properties (`Keys`) from `Type`.

*   **Mental Model:** "I only want *these* specific fields."
*   **Behavior:** If you add a new field to the original type, the `Pick`ed type **will not** have it unless you explicitly add it to the keys.

### Example

```typescript
interface User {
  id: number;
  name: string;
  email: string;
  passwordHash: string;
  createdAt: Date;
}

// We want a type for displaying a user profile card
type UserProfile = Pick<User, "name" | "email">;

const profile: UserProfile = {
  name: "Alice",
  email: "alice@example.com"
  // id, passwordHash, createdAt are NOT allowed
};
```

## 2. `Omit<Type, Keys>` (The Blacklist)

`Omit` constructs a type by picking all properties from `Type` and then removing `Keys`.

*   **Mental Model:** "I want everything *except* these specific fields."
*   **Behavior:** If you add a new field to the original type, the `Omit`ted type **will** automatically include it.

### Example

```typescript
interface User {
  id: number;
  name: string;
  email: string;
  passwordHash: string;
  createdAt: Date;
}

// We want a type for the user object, but without sensitive data
type SafeUser = Omit<User, "passwordHash">;

const user: SafeUser = {
  id: 1,
  name: "Alice",
  email: "alice@example.com",
  createdAt: new Date()
  // passwordHash is NOT allowed
};
```

## 3. Which one to use?

The choice depends on how you want your derived type to react when the base type evolves.

| Feature | `Pick` | `Omit` |
| :--- | :--- | :--- |
| **Approach** | Whitelist (Inclusive) | Blacklist (Exclusive) |
| **Stability** | **Rigid**: New props on base type are ignored. | **Flexible**: New props on base type are included. |
| **Best For** | Specific sub-views, DTOs, strict contracts. | Removing metadata, sensitive fields, or internal props. |

### Scenario: Adding a field
If we add `avatarUrl: string` to `User`:
*   `UserProfile` (Pick) will **not** have `avatarUrl`.
*   `SafeUser` (Omit) **will** have `avatarUrl`.

[[programming/javascript/typescript/typescript]]
[[programming/javascript/typescript/utility-types]]