CodexBloom - Programming Q&A Platform

TypeScript: Why is my mapped type not inferring the correct keys when using `keyof`?

πŸ‘€ Views: 77 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-09
typescript mapped-types keyof TypeScript

I'm trying to create a mapped type in TypeScript that infers keys from an existing interface, but I'm running into issues with the inferred types not working as expected. I'm using TypeScript 4.5.2, and I have the following interface: ```typescript interface User { id: number; name: string; email?: string; } ``` I want to create a type that maps to the keys of the `User` interface but modifies the types of each property. Here's my attempt: ```typescript type UserProperties = keyof User; type MappedUser = { [K in UserProperties]: string; }; ``` When I attempt to use this `MappedUser` type, I get the following behavior: ``` Type 'string' is not assignable to type 'number' | 'string' | undefined. ``` I expected `MappedUser` to have all properties of `User`, but with their types changed to `string`. What am I missing? I've also tried using `Pick` to narrow down the keys, but that didn't help either: ```typescript type MappedUser = { [K in keyof Pick<User, 'name' | 'email'>]: string; }; ``` That still gives me the same behavior when I try to use it in a function like this: ```typescript function updateUser(user: MappedUser) { console.log(user); } const newUser: MappedUser = { id: '1', name: 'Alice', email: 'alice@example.com' }; // behavior here ``` What’s the correct way to create a type that maps existing keys while changing the types of these keys? Is there a best practice for handling such cases? Thanks for any insights! Any help would be greatly appreciated! For context: I'm using Typescript on CentOS. Am I approaching this the right way?