Backbencher.dev

Setting Constraints for Generic Types in TypeScript

Last updated on 12 Feb, 2023

We can set constraints to Generic types. Constraints allow us to accept only certain types that can be passed as generic types.

Here is a generic function:

function mergeObject<T, U>(obj1: T, obj2: U) {
  return Object.assign(obj1, obj2);
}

We want both arguments to be objects. Then only the function works properly. What if we are invoking the function as below:

mergeObject({ name: "Joby" }, 30);

In the above function, second argument is a number. That was not intended.

TypeScript provides a way to constraint the type of T or U. Here is how we restrict T and U to be an object.

function mergeObject<T extends object, U extends object>(obj1: T, obj2: U) {
  return Object.assign(obj1, obj2);
}

Using the extends keyword, we can make sure that the passed type is constrained to certain type.

--- ○ ---
Joby Joseph
Web Architect