CodexBloom - Programming Q&A Platform

How to Type a Function that Merges Two Objects in TypeScript with Specific Property Constraints?

๐Ÿ‘€ Views: 473 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-11
typescript type-inference generics TypeScript

I'm sure I'm missing something obvious here, but I've hit a wall trying to I've searched everywhere and can't find a clear answer... I'm sure I'm missing something obvious here, but I'm trying to implement a function in TypeScript that merges two objects, but I want to ensure that the properties of the resulting object are constrained based on the properties of the input objects... For instance, if I have an object type `A` with properties `{ name: string, age: number }` and another object type `B` with properties `{ age: string, address: string }`, the resulting merged object should have properties `{ name: string, age: number | string, address: string }`. I have written the following code: ```typescript type A = { name: string; age: number; }; type B = { age: string; address: string; }; function mergeObjects<T, U>(obj1: T, obj2: U): { [K in keyof T | keyof U]: T[K] | U[K] } { return { ...obj1, ...obj2 }; } const a: A = { name: 'John', age: 30 }; const b: B = { age: 'thirty', address: '123 Main St' }; const merged = mergeObjects(a, b); console.log(merged); ``` However, when I run this, I get an behavior about incompatible types, specifically regarding the `age` property. TypeScript complains that `T[K]` and `U[K]` want to be merged because `number` and `string` are incompatible types. I tried using intersections and union types in various combinations, but I keep hitting a wall with TypeScriptโ€™s strict type checking. How can I properly type this merge function to allow for the properties of both objects while ensuring that the merged types reflect the correct constraints? My TypeScript version is 4.4.3. Any insights would be greatly appreciated! How would you solve this? My development environment is Windows. Any ideas what could be causing this? I'm open to any suggestions. Could this be a known issue?