⊗tsSpGnPTL 36 of 37 menu

Using Type Parameters in Generic Constraints in TypeScript

TypeScript also has the ability to declare one type parameter that will be constrained by another type parameter. This is necessary when you have to copy properties from one object to another, while ensuring that we do not pass an extra property.

Let's look at the following example. Let's go back to the function myFunc, which determines the length of the variable:

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

However, now we want this function to work only with those types that have a length property. To do this, we will create an interface ILength, to which we will assign the property length of the numeric type:

interface ILength { length: number; }

Next, in our function, we define a generic type that inherits from ILength via the keyword extends:

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

This is what our full code looks like:

interface 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 the string:

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

The result of the executed code:

5 'abcde'

Now let's pass the array to the parameter:

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

The result of the executed code:

3 [ 'a', 'b', 'c' ]
byenru