Opposite of "Pick" in Typescript

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 }


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

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

Tags:

Typescript