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?
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.
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.
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.
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.
Per @Thomas comment, in newer TS compilers, we can simply do:
const foo = <T,>(x: T) => x;
The full example explaining the syntax referenced by Robin... brought it home for me:
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With