Course contentsShow
← TypeScript
Lesson 543 of 1,79613. GenericsFree lesson

Generic Arrow Functions

Writing generic arrow functions and understanding the syntax differences, especially in TSX files.

Generic Arrow Functions

What you'll learn: How to write generic arrow functions in TypeScript and handle the special syntax needed in TSX files.

Writing Generic Arrow Functions

You already know how to write generic functions with the function keyword. Arrow functions can be generic too, using the same type parameter syntax:

// Regular generic function
function identity<T>(value: T): T {
  return value;
}

// Generic arrow function
const identity = <T>(value: T): T => {
  return value;
};

// Shorter version
const identity = <T>(value: T): T => value;

The type parameter <T> appears right before the parameter list, just like in regular functions. All the same rules apply: type inference works, you can use multiple type parameters, and you can pass explicit type arguments.

const map = <T, U>(array: T[], fn: (item: T) => U): U[] => {
  return array.map(fn);
};

// Inference works
map([1, 2, 3], n => n.toString()); // string[]

// Explicit type arguments work too
map<number, string>([1, 2, 3], n => n.toString());

The TSX Syntax Problem

In TSX files (React with TypeScript), the <T> syntax creates ambiguity because < is also used for JSX tags. TypeScript can't tell if you're writing a generic or opening a component.

Solution: Add a comma or constraint after the type parameter:

// Won't work in TSX - looks like a tag
const identity = <T>(value: T): T => value;

// Works in TSX
const identity = <T,>(value: T): T => value;
// OR
const identity = <T extends unknown>(value: T): T => value;

Key Takeaway: Generic arrow functions use the same <T> syntax as regular functions, but in TSX files you must add a trailing comma or constraint to avoid syntax ambiguity with JSX tags.