patterntypescriptCritical
What is the syntax for Typescript arrow functions with generics?
Viewed 0 times
typescriptfunctionswithgenericsarrowsyntaxtheforwhat
Problem
The typescript handbook currently has nothing on arrow functions. Normal functions
can be generically typed with this syntax:
example:
What is the syntax for arrow functions?
can be generically typed with this syntax:
example:
function identity(arg: T): T {
return arg;
}What is the syntax for arrow functions?
Solution
Edit
Per @Thomas comment, in newer TS compilers, we can simply do:
Original Answer
The full example explaining the syntax referenced by Robin... brought it home for me:
Generic functions
Something like the following works fine:
However using an arrow generic function will not:
Workaround: Use extends on the generic parameter to hint the compiler
that it's a generic, e.g.:
Per @Thomas comment, in newer TS compilers, we can simply do:
const foo = (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(x: T): T { return x; }However using an arrow generic function will not:
const foo = (x: T) => x; // ERROR : unclosed `T` tagWorkaround: Use extends on the generic parameter to hint the compiler
that it's a generic, e.g.:
const foo = (x: T) => x;Code Snippets
const foo = <T,>(x: T) => x;function foo<T>(x: T): T { return x; }const foo = <T>(x: T) => x; // ERROR : unclosed `T` tagconst foo = <T extends unknown>(x: T) => x;Context
Stack Overflow Q#32308370, score: 1180
Revisions (0)
No revisions yet.