HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptCritical

What is the syntax for Typescript arrow functions with generics?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescriptfunctionswithgenericsarrowsyntaxtheforwhat

Problem

The typescript handbook currently has nothing on arrow functions. Normal 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:

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` tag


Workaround: 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` tag
const foo = <T extends unknown>(x: T) => x;

Context

Stack Overflow Q#32308370, score: 1180

Revisions (0)

No revisions yet.