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 }
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>>;
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With