TypeScript Inference guide with Mapped Types and Conditional Types in Generic Classes
I've been researching this but I'm having trouble with I'm working with an scenario with TypeScript's type inference when using mapped types alongside conditional types in a generic class. I'm trying to create a utility class that transforms an object type into another based on a specific condition. Here's the class I'm working with: ```typescript type Transform<T> = { [K in keyof T]: T[K] extends string ? number : T[K]; }; class Transformer<T> { constructor(private data: T) {} transform(): Transform<T> { const transformed = {} as Transform<T>; for (const key in this.data) { if (typeof this.data[key] === 'string') { transformed[key] = this.data[key].length; // Transform string to its length } else { transformed[key] = this.data[key]; } } return transformed; } } ``` When I try to instantiate the class like this: ```typescript const inputData = { name: 'Alice', age: 30 }; const transformer = new Transformer(inputData); const result = transformer.transform(); ``` I get the following behavior: ``` Type 'Transform<{ name: string; age: number; }>' is not assignable to type '{ name: number; age: number; }'. Property 'name' is incompatible with index signature. ``` It seems TypeScript is not inferring the return type of `transform` correctly. I've attempted to specify the return type explicitly by modifying the `transform` method header, like this: ```typescript the transform(): Transform<T> { ``` However, the scenario continues. I've also tried to narrow the type of `data` within the class to make sure TypeScript understands the transformation logic, but that didn't help either. Can anyone provide insight into why TypeScript isn't able to correctly infer the types in this context and how I can resolve this scenario? I am using TypeScript version 4.5.2. My development environment is Windows. Any ideas what could be causing this? I'm working on a application that needs to handle this. What would be the recommended way to handle this?