TypeScript generic constraint optimization guide as expected with a mapped type in a utility function
I'm trying to create a utility function in TypeScript that accepts an array of objects and returns a new object mapping the specified keys to their respective values. I want to use generics with constraints to ensure that the function only accepts arrays of objects with specific properties, but I keep running into issues with the type inference. Here's the code I have: ```typescript type KeyValueMap<T, K extends keyof T> = { [key in K]: T[key]; }; function mapKeys<T, K extends keyof T>(arr: T[], keys: K[]): KeyValueMap<T, K>[] { return arr.map(item => { const result = {} as KeyValueMap<T, K>; keys.forEach(key => { result[key] = item[key]; }); return result; }); } interface User { id: number; name: string; age: number; } const users: User[] = [ { id: 1, name: 'Alice', age: 25 }, { id: 2, name: 'Bob', age: 30 } ]; const mappedUsers = mapKeys(users, ['id', 'name']); console.log(mappedUsers); ``` However, when I try to run this code, I get the following behavior: `Type 'K' is not assignable to type 'key'` on the line where I assign `result[key] = item[key];`. It seems like TypeScript isn't correctly inferring that `key` is indeed a key of `item`. I've tried using `as` to cast the type, but that doesn't seem to resolve the scenario. Is there a better way to enforce the constraints on `key` and ensure that the mapping works as intended? I also checked that my TypeScript version is 4.5.2, and I wonder if this could be a version-related question or if I'm just misunderstanding how to apply generics and constraints in this scenario. Any help would be greatly appreciated!