Generic merge with an intersection return type
Generics and intersection types.
Use two type parameters T and U, return T & U, spread both objects; note later spread wins on key collisions and the type may not reflect that.
WHAT THIS TESTS Your fluency with generic type parameters, intersection types, and the object spread, plus awareness of the edge case where runtime behavior and the static type diverge on overlapping keys.
A GOOD ANSWER COVERS A correct solution is generic over both inputs and returns their intersection. function merge<T extends object, U extends object>(a: T, b: U): T & U { return { ...a, ...b }; } The two type parameters preserve the exact shapes of the arguments, and the return type T & U tells the compiler the result carries every property of both, so callers get full autocomplete and type checking without casts. The constraint extends object keeps callers from passing primitives. A strong candidate flags the collision case: if both objects share a key, the spread keeps the second object's value at runtime, but the intersection type can model the property as having both source types, which can be a subtle source of confusion.
COMMON WRONG ANSWERS Returning any or Record<string, unknown>, throwing away type safety. Hardcoding User and Product instead of using generics. Using Object.assign without typing the result. Ignoring what happens when keys overlap. Forgetting the extends object constraint and allowing primitives.
LIKELY FOLLOW-UPS What happens to the type and value when both objects have the same key? How would you deep-merge instead of shallow? How do you exclude undefined values? Could you type this with mapped types for stricter overlap handling?
ONE CONCRETE EXAMPLE Given const u: User = { id: 1, name: 'Ada' } and const p: Product = { sku: 'X1', price: 9 }, calling merge(u, p) yields a value typed as User & Product, so result.name and result.price both type-check and autocomplete. If User had price too, the runtime value would take Product's price because b is spread last, while TypeScript would type the price property from the intersection, a divergence worth naming in the interview.
Read the original → typescriptlang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.