Generic Constraints with Object Spread
You'll learn how to write type-safe generic functions that spread objects while enforcing constraints on what can be merged.
When you write a function that spreads a generic object, TypeScript doesn't automatically know what properties that object has. Without constraints, you can't safely spread it or guarantee type safety for the result.
The Problem Without Constraints
If you try to spread a completely unknown generic type, TypeScript can't verify what properties exist or how they'll merge:
function merge<T>(obj: T) {
return { ...obj, added: true }; // Works, but T could be anything
}
Adding Object Constraints
Use extends object (or a more specific shape) to tell TypeScript the generic must be an object type:
function merge<T extends object>(obj: T) {
return { ...obj, added: true };
}
const result = merge({ name: "Alice" });
// Type: { name: string; added: boolean }
Now TypeScript knows T is spreadable and can infer the merged result type correctly.
Multiple Generic Parameters
For merging two objects, constrain both:
function combine<T extends object, U extends object>(first: T, second: U) {
return { ...first, ...second };
}
const merged = combine({ a: 1 }, { b: "hi" });
// Type: { a: number; b: string }
The constraint ensures both arguments are objects, and TypeScript correctly types the spread result.
Key Takeaway: Use extends object on generic type parameters when spreading them—this enforces that the type is spreadable and enables accurate type inference for the merged result.