TypeScript - how to infer types when using generics with a mapped type and a conditional type
I'm currently working on a TypeScript project (v4.5) where I'm trying to create a generic function that accepts an object and returns a mapped type based on its properties. However, I'm running into an scenario with type inference when using a conditional type inside a mapped type. Here's what my code looks like: ```typescript type Transform<T> = { [K in keyof T]: T[K] extends string ? number : T[K] }; function transformObject<T>(obj: T): Transform<T> { const result = {} as Transform<T>; for (const key in obj) { if (typeof obj[key] === 'string') { result[key] = obj[key].length; } else { result[key] = obj[key]; } } return result; } ``` I'm trying to transform an object so that if a property is a string, it gets converted to its length (a number), but if it's any other type, it should remain unchanged. However, when I try to call `transformObject` like this: ```typescript const input = { name: 'Alice', age: 30, isActive: true }; const transformed = transformObject(input); console.log(transformed); ``` I get this TypeScript behavior: `Type '{ name: number; age: number; isActive: boolean; }' is not assignable to type 'Transform<{ name: string; age: number; isActive: boolean; }>'.` It seems like TypeScript is not correctly inferring the return type when the object has mixed property types. I've tried adjusting the generic constraints and even using `as` assertions, but nothing seems to work. Is there a way to make TypeScript correctly infer the types in this scenario? Any insights or suggestions would be greatly appreciated! What's the best practice here?