Picture a scenario where you have an interface like this:
interface Person {
name: string;
age: number;
height: number;
}
Now, imagine having a function that accepts an array of keys from the interface and returns an object with only those specified keys.
const person: Person = {
name: 'John Doe',
age: 30,
height: 175,
}
const getPartialPerson = (keys: keyof Person[]) => {
return Object.keys(person).reduce((acc, val) => {
if keys.includes(val) {
acc[val] = person[val]
}
return acc;
}, {});
}
const partialPerson = getPartialPerson(['name', 'age']);
partialPerson.name; // should be valid
partialPerson.age; // should be valid
partialPerson.height; // ERROR: does not exist in type
The goal is to allow the type to automatically determine the valid properties based on the input array.
Although it seems achievable, I am struggling to make it happen.
One possible approach could involve something like this:
const getPartialPerson = <T extends keyof Person>(keys: keyof T[]): Pick<Person, T> => {
....
}