Languages
[Edit]
EN

TypeScript - generic arrow function

10 points
Created by:
maciek211
335

In this quick article we are going to look at how to create generic arrow function In TypeScript.

The presented solution works for * .ts files - for * .tsx files, the problem solution is included in the Note under the first example.

Quick solution:

let print1 = <T>                 (entry: T) : void => { consle.log(entry); };
let print2 = <T extends unknown> (entry: T) : void => { consle.log(entry); };
let print3 = <T extends User>    (entry: T) : void => { consle.log(entry.toText()); };

print1(100);    // 100
print1(true);   // true
print1('text'); // text

Note:

  • by giving an argument to a print function, the compiler automatically detects the argument type, so no type call is needed:
    • print<number>(100),
    • print<boolean>(true),
    • print<string>('text'),
  • for * .tsx files the following notation should be used:
    let print = <T extends {}> (entry: T) : void => { /* code */ }

More complex example

In this example, we used a generic arrow function to iterate through an array. The iterate function takes an array and references to the iterating function. Both arguments are generic so we can work with array elements of different types.

interface Iteration<T> {
    (index : number, item : T) : void;
}

let iterate = <T> (array : Array<T>, iteration : Iteration<T>) : void => {
    for(let i = 0; i < array.length; ++i)
        iteration(i, array[i]);
};


let array : Array<number> = [ 1, 2, 3 ];

let iteration = (index : number, item : number) : void => {
    console.log(`${index} : ${item}`);
};

iterate(array, iteration);

Output:

0 : 1
1 : 2
2 : 3

Run it online here.

TypeScript

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join