EN
TypeScript - generic arrow function
7
points
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.