CodexBloom - Programming Q&A Platform

TypeScript: implementing Dynamic Object Keys and Type Safety in a Mapped Type

👀 Views: 1399 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
typescript mapped-types type-inference TypeScript

I'm experimenting with I'm working on a personal project and I'm working with an scenario trying to create a dynamic object with keys that are based on a union type, and I want to ensure that TypeScript enforces type safety. Specifically, I have a union of strings representing keys and I want to map these keys to a specific type of value. My goal is to create an object that adheres to this mapping without running into type errors. Here's the code that I've been working with: ```typescript type Keys = 'name' | 'age' | 'email'; interface UserProfile { name: string; age: number; email: string; } type MappedProfile = { [K in Keys]: UserProfile[K]; }; const user: MappedProfile = { name: 'Alice', age: 30, email: 'alice@example.com', }; // Trying to dynamically add a new property const addUserProfile = <K extends Keys>(key: K, value: UserProfile[K]) => { user[key] = value; // behavior: want to assign to 'key' because it is a read-only property. }; addUserProfile('name', 'Bob'); ``` I'm getting a TypeScript behavior that says: `want to assign to 'key' because it is a read-only property.` I understand that TypeScript is enforcing the rules based on the mapped type, but I'm not sure how to properly implement this function without losing the type inference. I've tried using type assertions and different approaches, but I keep running into issues. Is there a recommended way to handle this when dealing with mapped types and dynamic keys in TypeScript? I'm currently using TypeScript v4.4.3, and I want to ensure that my implementation is both type-safe and flexible. Has anyone else encountered this? Any help would be greatly appreciated!