CodexBloom - Programming Q&A Platform

TypeScript Inference Issues with Mapped Types and Conditional Types in Utility Functions

πŸ‘€ Views: 44 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-30
typescript type-inference mapped-types TypeScript

I'm getting frustrated with I'm maintaining legacy code that After trying multiple solutions online, I still can't figure this out... I'm facing an issue with TypeScript's type inference when using mapped types in combination with conditional types for a utility function. The goal is to create a function that takes an object and returns a new object with the same keys but with values transformed based on a condition. I'm using TypeScript 4.6, and I want to ensure that the output type accurately reflects the transformation. Here’s an example of what I've implemented: ```typescript type Transform<T> = { [K in keyof T]: T[K] extends number ? string : T[K]; }; function transformObject<T>(obj: T): Transform<T> { const result = {} as Transform<T>; for (const key in obj) { if (typeof obj[key] === 'number') { result[key] = obj[key].toString() as any; } else { result[key] = obj[key]; } } return result; } const input = { a: 1, b: 'hello', c: 3 }; const output = transformObject(input); console.log(output); ``` The issue arises when I try to call `transformObject` with the `input` object. TypeScript infers the type of `output` as `{ a: string; b: string; c: string; }` instead of `{ a: string; b: string; c: number; }`. This is incorrect because I want to keep the type of non-number properties untouched. I've tried adjusting the `Transform<T>` definition and used different methods of type assertion, but I keep running into situations where the output type still doesn't match my expectations. The TypeScript compiler's output suggests that the transformation is too aggressive and overrides the original types indiscriminately. Is there a better way to manage this transformation to maintain the integrity of the non-number types while still transforming the number types? Any insights on how to resolve this or best practices for achieving this functionality would be greatly appreciated. I'm working on a API that needs to handle this. I'd really appreciate any guidance on this. My team is using Typescript for this CLI tool. Hoping someone can shed some light on this.