Published on

Understanding TypeScript's Omit<T, K> Utility Type

Authors
  • avatar
    Name
    hwahyeon
    Twitter

Omit<T, K> is a utility type provided by TypeScript that creates a new type by removing the properties K from type T. This type is implemented by combining two other utility types, Pick and Exclude. Using this approach, it creates a type that excludes the properties specified in K and includes only the remaining properties of T.

Example

type Person = {
  name: string
  age: number
  address: string
}

type WithoutAddress = Omit<Person, 'address'>
// Result: { name: string; age: number; }

const person: WithoutAddress = {
  name: 'Alice',
  age: 30,
  // address: "123 Street" // Error
}

How Omit is Implemented

Omit is defined by combining the TypeScript utility types Pick and Exclude. The actual implementation in TypeScript is as follows:

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>

How It Works

  • keyof T: Retrieves all the property keys of type T.
  • Exclude<keyof T, K>: Removes the keys specified in K from T, returning the remaining keys.
  • Pick<T, Exclude<keyof T, K>>: Selects only the properties corresponding to the remaining keys from T to create a new type.

Internal Example

type Person = {
  name: string
  age: number
  address: string
}

// Omit<Person, "address"> works as follows:
type WithoutAddress = Pick<Person, Exclude<keyof Person, 'address'>>
    1. keyof Person "name" | "age" | "address"
    1. Exclude<keyof Person, "address">"name" | "age" → The "address" key is removed.
    1. Pick<Person, "name" | "age">{ name: string; age: number }