I'm creating a generic function that gets properties from an object using array.reduce. I would like the return type to only return the type of properties extracted from the original object
type Sample = {
name: string;
age: number;
isAlive: boolean;
}
const sample: Sample = {
name: "John Doe",
age: 22,
isAlive: true,
};
// What changes should I do here?
function getProps(...keys: (keyof Sample)[]) {
return keys.reduce((acc, key) => {
acc[key] = sample[key];
return acc;
}, {})
}
const result = getProps("name", "age");
/*
I would like the result to have a type of:
{
name: string;
age: number;
}
*/
I saw this being done in zustand.js but I don't know how they did it. Any help is appreciated.
CodePudding user response:
Here's a quick solution. The key is using generics and the Pick
utility type:
type Sample = {
name: string;
age: number;
isAlive: boolean;
}
const sample: Sample = {
name: "John Doe",
age: 22,
isAlive: true,
};
function getProps<K extends keyof Sample>(...keys: K[]): Pick<Sample, K> {
return keys.reduce((acc, key) => {
acc[key] = sample[key];
return acc;
}, {} as Pick<Sample, K>)
}
const result = getProps("name", "age");
// result has only name and age