Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the syntax for Typescript arrow functions with generics?

Tags:

typescript

The typescript handbook currently has nothing on arrow functions. Normal functions can be generically typed with this syntax: example:

function identity<T>(arg: T): T {
    return arg;
}

What is the syntax for arrow functions?

like image 434
Andreas Frische Avatar asked Aug 31 '15 09:08

Andreas Frische


People also ask

What is the syntax of an arrow function?

Arrow Function Syntax The syntax of the arrow function is: let myFunction = (arg1, arg2, ...argN) => { statement(s) } Here, myFunction is the name of the function. arg1, arg2, ... argN are the function arguments.

How do I use TypeScript generics?

By passing in the type with the <number> code, you are explicitly letting TypeScript know that you want the generic type parameter T of the identity function to be of type number . This will enforce the number type as the argument and the return value.

How do you define a generic type in TypeScript?

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.

Does TypeScript have generics?

TypeScript supports generic classes. The generic type parameter is specified in angle brackets after the name of the class. A generic class can have generic fields (member variables) or methods.


2 Answers

Edit

Per @Thomas comment, in newer TS compilers, we can simply do:

const foo = <T,>(x: T) => x;

Original Answer

The full example explaining the syntax referenced by Robin... brought it home for me:

Generic functions

Something like the following works fine:

function foo<T>(x: T): T { return x; }

However using an arrow generic function will not:

const foo = <T>(x: T) => x; // ERROR : unclosed `T` tag

Workaround: Use extends on the generic parameter to hint the compiler that it's a generic, e.g.:

const foo = <T extends unknown>(x: T) => x;
like image 70
jbmilgrom Avatar answered Oct 11 '22 21:10

jbmilgrom


If you're in a .tsx file you cannot just write <T>, but this works:

const foo = <T, >(x: T) => x;

As opposed to the extends {} hack, this hack at least preserves the intent.

like image 281
mb21 Avatar answered Oct 11 '22 23:10

mb21