In the codebase I'm working on, I recently added a useful util function:
const pick = <T extends object, P extends keyof T, R = Pick<T,P>>(
obj: T,
keys: P[]
): R => {
if (!obj) return {} as R
return keys.reduce((acc, key) => {
return {...acc, [key]:obj[key] };
}, {} as R)
};
The function is functioning correctly and TypeScript correctly infers the return type. However, there's one issue with the 'keys' parameter - I want to restrict it based on previously chosen keys.
For example:
const obj = {name: 'John Doe', age: '33', city: 'NYC'}
// When providing keys in the array parameter, TypeScript infers them correctly
const a = pick(obj, ['name', 'age'])
// HOWEVER, this is also allowed without any errors from TypeScript
const b = pick(obj, ['name', 'age', 'age'])
// Moreover, If I've already typed 'name', I want the editor to suggest only 'age' and 'city' as options, but currently all keys are still shown.
I've tried various solutions (including currying), but haven't been successful yet. It seems like a challenging TypeScript puzzle. Any help would be greatly appreciated!