Using Type Parameters in Generic Constraints in TypeScript

TypeScript also allows the declaration of one type parameter that will be constrained by another type parameter. This is necessary when you need to copy properties from one object to another while ensuring that we do not pass an extra property.

Let's consider the following example. Let's return to the myFunc function that determines the length of a variable:

typescriptfunction myFunc <T> (data: T): T {
  console.log(data.length); // error
  return data;
}

However, now we want this function to work only with types that have the length property. To do this, let's create an interface ILength and assign it the length property of the numeric type:

typescriptinterface ILength {
  length: number;
}

Next, in our function, we will specify a generic type that inherits from ILength using the extends keyword:

typescriptfunction myFunc <T extends ILength> (data: T): T {
  console.log(data.length);
  return data;
}

Here is our full code:

typescriptinterface ILength {
  length: number;
}

function myFunc <T extends ILength> (data: T): T {
  console.log(data.length);
  return data;
}

Let's test our function and find the length of a string:

typescriptconsole.log(myFunc('abcde'));

The result of the executed code:

typescript5
'abcde'

And now let's pass an array as a parameter:

typescriptconsole.log(myFunc(['a', 'b', 'c']));

The result of the executed code:

typescript3
[ 'a', 'b', 'c' ]