Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of "Pick" in Typescript

Tags:

typescript

I am trying to compose a type, which, unlike Pick, would remove certain properties from the object type.

It should work this way:

type ObjectType = { 
    key1: number, 
    key2: string, 
    key3: boolean, 
    key4: number[] 
}

let obj: Remove<ObjectType, 'key2' | 'key4'>

Here obj's type should be: { key1: number, key3: boolean }

like image 619
Eduard Avatar asked Sep 26 '18 14:09

Eduard


2 Answers

As of TypeScript 3.5, there is an Omit helper that works as you describe.

type ObjectType = { 
    key1: number, 
    key2: string, 
    key3: boolean, 
    key4: number[] 
}

let obj: Omit<ObjectType, 'key2' | 'key4'> // type is { key1: number, key3: boolean }

For older versions of TypeScript (>2.8), you can use a combination of Pick and Exclude as mentioned by Eduard in his answer.

I often make a helper type to make things a bit less verbose (note this is the exact definition used in TS 3.5)

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
like image 140
Josiah Nunemaker Avatar answered Sep 20 '22 15:09

Josiah Nunemaker


If we need to remove properties key2 and key4, this will work:

type Without<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

let obj: Without<ObjectType, 'key2' | 'key4'>

Elaboration:

Exclude<keyof T, K> returns 'key1' | 'key3'

Pick<T, Exclude<keyof T, K>> returns the desired result { key1: number, key3: boolean }

like image 24
Eduard Avatar answered Sep 17 '22 15:09

Eduard