zedryas
zedryas

Reputation: 974

PickIfContains type to pick in an object whether the keys belongs to the object definition or not

I'm trying to build a type that will Pick any key of an object if the object contains the key (independently of the fact the key is defined on the type of the object or not. (Pick needs keys that belongs to the type of the object)

type PickIfContains <T, K extends string []> = {
  [P in K [number]]: P extends keyof T ? T [P] : never
}

type A = {a: number, b: number}
type B = PickIfContains <A, ['a', 'c']>
// GIVEN: {a: number, c: never}
// EXPECTED: {a: number}

How can I remove in the resulting type the keys that are set to never ?

Upvotes: 1

Views: 32

Answers (2)

maxime1992
maxime1992

Reputation: 23803

Yes I believe you can do something more simple than your answer

type PickIfContains<T, K extends string> = {
    [L in Extract<keyof T, K>]: T[L]
}

Live demo

Upvotes: 1

zedryas
zedryas

Reputation: 974

I did found an answer It's just a tad verbose

type PickIfContains <T, K extends string []> = {
  [
    P in {
      [P in K [number]]: P extends keyof T ? P : never
    } [K [number]]
  ]: T [P]
}

If anyone has a better solution don't hesitate ;)

Upvotes: 0

Related Questions