CodexBloom - Programming Q&A Platform

How to Avoid Type Errors When Using Mapped Types with Optional Properties in TypeScript 4.5?

👀 Views: 85 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
typescript mapped-types optional-properties

I'm confused about I'm working on a project and hit a roadblock... I'm relatively new to this, so bear with me. I'm working with a type behavior in TypeScript 4.5 when trying to use mapped types with optional properties. I have a type that represents a configuration object with several optional fields, and I want to create a mapped type that transforms these fields into another type, ensuring that the optional fields remain optional. Here's what I've tried: ```typescript type Config = { name?: string; age?: number; active?: boolean; }; type TransformedConfig<T> = { [K in keyof T]: T[K] extends string ? number : T[K]; }; type NewConfig = TransformedConfig<Config>; ``` When I attempt to use `NewConfig`, TypeScript throws the behavior: `Type 'string | undefined' is not assignable to type 'number | undefined'`. This seems to happen because TypeScript doesn't recognize that the properties remain optional after the transformation. I've also tried using `Partial<Config>` like this: ```typescript type NewConfig = { [K in keyof Config]: Config[K] extends string ? number : Config[K]; }; ``` However, this still leads to the same behavior regarding optional properties. I need a solution that allows me to map the types without losing the optional nature of the properties. Is there a way to achieve this? Any tips or best practices would be greatly appreciated! I'm working on a CLI tool that needs to handle this. I'd really appreciate any guidance on this. My development environment is macOS. Am I missing something obvious? What's the correct way to implement this?