Write a typesafe 'pick' function in typescript
Sounds like you might be looking for the Pick type. Would something like this work for you?
function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
const ret: any = {};
keys.forEach(key => {
ret[key] = obj[key];
})
return ret;
}
const o = {a: 1, b: '2', c: 3}
const picked = pick(o, 'b', 'c');
picked.a; // not allowed
picked.b // string
picked.c // number
With Object.fromEntries
(es2019):
function pick<T extends object, K extends keyof T> (base: T, ...keys: K[]): Pick<T, K> {
const entries = keys.map(key => ([key, base[key]]));
return Object.fromEntries(entries);
}