I am enhancing my pick
function and here is my current implementation:
export function pick<T, K extends keyof T>(obj: T, keys: K[]): Partial<T> {
const ret = Object.create(null)
for(const key of keys) {
ret[key] = obj[key]
}
return ret
}
This is what I aim to achieve:
export function pick<T, K extends keyof T>(obj: T, keys: K[]): K is keyof T ? T : Partial<T>
In other words, when all keys of T
are passed, TypeScript should understand that it will return a complete T
. If a subset of keys is provided, it should return a Partial<T>
(or ideally, something like if K is in T, then T[K], otherwise undefined
).
Is this feasible? It seems I can only use extends
conditionals, not "exactly is" conditionals.
Alternatively, can I define the return type as something like {[K in keyof T]: T[K]}
? However, I am unsure how to specify that the remaining keys will be undefined
by negating in keyof
.
The Pick<>
helper is not suitable in this case because my approach differs - I always return exactly K
keys.