CodexBloom - Programming Q&A Platform

TypeScript: Using Mapped Types for Partial Object Assignments with Default Values

👀 Views: 13 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
typescript mapped-types utility-types TypeScript

I've encountered a strange issue with I'm working on a personal project and I'm upgrading from an older version and I'm trying to figure out I'm relatively new to this, so bear with me..... I'm facing an issue while trying to create a utility type in TypeScript that allows for partial object updates but also sets default values for missing properties. I have the following interface for a user profile: ```typescript interface UserProfile { name: string; age: number; email: string; } ``` I want to create a mapped type that allows me to specify only the properties I want to update, while also providing default values for any properties that are not included in the update. I tried the following approach: ```typescript type PartialUpdate<T> = { [K in keyof T]?: T[K]; }; const defaultValues: UserProfile = { name: 'Anonymous', age: 18, email: 'default@example.com', }; function updateUserProfile(profile: UserProfile, updates: PartialUpdate<UserProfile>): UserProfile { return { ...defaultValues, ...profile, ...updates }; } ``` However, when I run this code, I end up with the default values being overridden by the existing values of `profile` instead of using them when properties are missing in `updates`. For instance: ```typescript const currentProfile: UserProfile = { name: 'John Doe', age: 30, email: 'john@example.com', }; const updatedProfile = updateUserProfile(currentProfile, { age: 25 }); console.log(updatedProfile); ``` I expected the `updatedProfile` to have `name` as 'John Doe', `age` as 25, and `email` as 'default@example.com', but instead, it results in: ``` { name: 'John Doe', age: 25, email: 'john@example.com' } ``` It seems like the existing profile values are taking precedence over the default ones. How can I restructure my `updateUserProfile` function so that it uses the default values when properties are missing from `updates`? Any insights or best practices would be greatly appreciated. Is this even possible? I'd be grateful for any help. I'm working with Typescript in a Docker container on Ubuntu 20.04. Has anyone dealt with something similar? I've been using Typescript for about a year now. Thanks for any help you can provide!