- Published on
Understanding TypeScript's Omit<T, K> Utility Type
- Authors
- Name
- hwahyeon
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 typeT
.Exclude<keyof T, K>
: Removes the keys specified inK
fromT
, returning the remaining keys.Pick<T, Exclude<keyof T, K>>
: Selects only the properties corresponding to the remaining keys fromT
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'>>
keyof Person
→"name" | "age" | "address"
Exclude<keyof Person, "address">
→"name" | "age"
→ The"address"
key is removed.
Pick<Person, "name" | "age">
→{ name: string; age: number }