TypeScript Generic Constraints with Mapped Types Not Inferring Properly
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.