Eduard
Eduard

Reputation: 9175

Opposite of "Pick" in 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 }

Upvotes: 24

Views: 20111

Answers (3)

Josiah Nunemaker
Josiah Nunemaker

Reputation: 819

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>>;

Upvotes: 31

Ben Carp
Ben Carp

Reputation: 26568

You can use 'utility-types' Omit generic.

import { Omit } from "utility-types"

interface IHouse {
    rooms: number 
    gardenSize: number
    toilets: number
}

type Appartment = Omit<IHouse, "gardenSize">

Upvotes: 1

Eduard
Eduard

Reputation: 9175

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 }

Upvotes: 24

Related Questions