Languages
[Edit]
EN

TypeScript - generic arrow function

10 points
Created by:
maciek211
365

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 function, so there is no needed type in the calls:
    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.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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