⊗tsSpGnPTL 36 of 37 menu

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:

function 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:

interface ILength { length: number; }

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

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

Here is our full code:

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 a string:

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

The result of the executed code:

5 'abcde'

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

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

The result of the executed code:

3 [ 'a', 'b', 'c' ]
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline