Reputation: 974
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
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]
}
Upvotes: 1
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