What it is and why to use it
An arrow function can have a type parameter just like a named generic function. This preserves the relationship between an argument’s element type and the result. In a TSX file, a trailing comma in the generic parameter list helps distinguish this syntax from JSX markup.
Common mistakes and limitations
Do not return T when reading an unconstrained array index may produce undefined. Generic syntax does not prove that an element exists. TSX syntax rules also differ from an ordinary .ts file around angle brackets.
Run this example
Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.
Terminal — compile and run
npx tsc example.ts --strict --target ES2022 --module commonjs
node example.jsSyntax
const first = <T,>(values: readonly T[]): T | undefined => values[0];Examples
Generic Arrow Functions
Standalone TypeScript 5.8+ example; expected output is explained below.
const first = <T,>(values: readonly T[]): T | undefined => values[0];
console.log(first(["John", "James"]) ?? "Empty");
console.log(first<number>([]) ?? 0);- T is inferred as string for the first call, making the result string or undefined.
- The empty array call explicitly selects number and falls back to zero.
- The undefined branch matters because an array can be empty. The trailing comma is syntactic disambiguation, not an extra type parameter.
- Expected output: John 0
Best practices
- Do not return T when reading an unconstrained array index may produce undefined. Generic syntax does not prove that an element exists. TSX syntax rules also differ from an ordinary .ts file around angle brackets.
- Keep external-input validation separate from compile-time type descriptions.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook