⊗tsSpGnGTV 31 of 37 menu

Generic Type Variables in TypeScript

When we create a generic function, TypeScript forces us to use type variables correctly in its body. Therefore, we need to consider the behavior of each parameter passed to the function in terms of all the types available to us.

Let's create a function to determine the length of a generic variable:

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

The error occurs because not all types have a length. For example, for boolean values, this action is impossible. However, if we specify the type and specify it as an array, the code will work correctly. After all, every array, no matter what type it is, has a length:

function myFunc <T> (data: T[]): T[] { console.log(data.length); // 3 return data; } console.log(myFunc([1, 3, 5])); // [ 1, 3, 5 ]

Write a function to iterate over and output all elements of a generic array to the console.

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