I have the following generic function:
function getFoodProperties<T, K extends keyof T>(foods: T[], keys: K[]): any[] { // <-- any needs to be typed according to generic types?
return foods.map((food) => {
let obj: any = {}; // <-- this any also needs typing - it should be the same type as the one above I think?
keys.forEach((key) => {
obj[key] = food[key];
});
return obj;
});
}
const foods: IFoods[] = [
{ name: "Beef", colour: "Red", weight: 8 },
{ name: "Chips", colour: "Yellow", weight: 1 },
{ name: "Lettuce", colour: "Green", weight: 9 },
];
getFoodProperties(foods, ["name", "colour"]);
I have it mostly typed I think, but I'm having trouble typing the return for the new object shape. The object keys are being picked according to the items in the getFoodProperties second argument. It's so far outputting the correct data, but it's not typed.
It seems without assigning a type to the let obj, it errors with:
Type 'K' cannot be used to index type '{}'
So I believe I need to create a generic type used for the function return value, and the inner object in the foods map, but I'm not sure how to approach it.