EN
TypeScript - generic arrow function
10
points
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 solutions:
const print = <T> (entry: T) : void => {
console.log(entry);
};
print(100); // 100
or:
const print = <T extends unknown> (entry: T) : void => {
console.log(entry);
};
print(true); // true
or:
const print = <T extends User> (entry: T) : void => {
console.log(entry.toText());
};
print('text'); // text
Note:
- the compiler automatically detects the argument type in the
print<number>(100); print<boolean>(true); print<string>('text');
- for
* .tsx
files the following notation should be used:const 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;
}
const iterate = <T> (array : Array<T>, iteration : Iteration<T>) : void => {
for(let i = 0; i < array.length; ++i) {
iteration(i, array[i]);
}
};
const array : Array<number> = [ 1, 2, 3 ];
const iteration = (index : number, item : number) : void => {
console.log(`${index} : ${item}`);
};
iterate(array, iteration);
Output:
0 : 1
1 : 2
2 : 3
Run it online here.