⊗tsSpGnIms 35 of 37 menu

Limitations of Generics in TypeScript

In one of the previous lessons, we created a generic function that was supposed to output the length of the parameter passed to it. However, when compiling, we got an error because not all types can have a length:

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

In that case, we fixed the situation by changing the generic type to a generic array type. But TypeScript has the ability to create generic constraints. To do this, in angle brackets, after the variable T, we write the keyword extends. After it, in curly brackets, we write a new variable str of the string type. The rest of the function code will remain unchanged:

function myFunc <T extends {str: string}> (data: T): void { console.log(data.str.length); }

It turns out that the generic type inherits the type of the variable str specified in the curly braces. Now let's test our function and create a variable myStr referring to the type str and assign it the value in the curly braces:

let myStr: {str: string} = {str: 'abcde'};

Let's call the function myFunc, remembering to specify its type again and pass the variable myStr as a parameter:

myFunc <{str: string}> (myStr);

Based on the example discussed in the lesson, define a function to find the length of a numeric array.

byenru