CodexBloom - Programming Q&A Platform

TypeScript Generic Constraints with Mapped Types Not Inferring Properly

๐Ÿ‘€ Views: 0 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-12
typescript generics mapped-types TypeScript

I can't seem to get I'm working with an scenario with TypeScript where I'm trying to create a mapped type that uses generics and constraints, but it seems like the inferred types are not what I expected. Hereโ€™s an example: I have a generic function that accepts an object and I want to transform its properties into a new type, preserving the original keys but changing the values based on a condition. Hereโ€™s the code I have so far: ```typescript type User = { id: number; name: string; age: number; }; type Transform<T> = { [K in keyof T]: T[K] extends number ? string : T[K]; }; function transformUser<T>(user: T): Transform<T> { const transformed: Partial<Transform<T>> = {}; for (const key in user) { if (typeof user[key] === 'number') { transformed[key] = user[key].toString(); } else { transformed[key] = user[key]; } } return transformed as Transform<T>; } const user: User = { id: 1, name: 'Alice', age: 30 }; const transformedUser = transformUser(user); console.log(transformedUser); ``` When I run this code, the `transformedUser` variable has the type `Transform<User>` as expected, but I get an behavior when trying to assign a non-number type to it. The behavior message is: ``` Argument of type 'string' is not assignable to parameter of type 'string | number'. ``` I tried using `Partial<Transform<T>>` to initially create a partial object, but this seems to confuse TypeScript's inference. Also, I've attempted to add more constraints to the mapped type, but it didnโ€™t help. My TypeScript version is 4.5.2. Is there a better way to handle this or a different approach I should consider to make the type inference work correctly without hitting this behavior? I'd love to hear your thoughts on this.