/**
* Function to pick specific keys from an object.
*/
function pick<T, K extends keyof T> (obj: T, keys: K[]): Pick<T, K> {
return keys.reduce((result, key) => {
result[key] = obj[key];
return result;
}, {} as any);
}
const keys = ['b', 'c'];
const o = {a: 1, b: '2', c: 3};
const picked = pick(o, ['b', 'c']); // This is valid
const picked2 = pick(o, keys); // This will produce an error
Error message: Argument of type 'string[]' is not assignable to parameter of type '("a" | "b" | "c")[]'.
If you only want to dynamically select keys, consider using a union type for the keys instead of an array of strings.