Languages
[Edit]
EN

TypeScript - generic arrow function

7 points
Created by:
Kate_C
2943

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

Quick solution:

let print = <T> (entry: T) : void => {
    consle.log(entry);
};

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

1. Loop with generic arrow function example

In this example we used generic arrow function to iterate over array.

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.

Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.