How to Make An Arrow Function Generic In TypeScript

You can use generics with arrow functions by specifying the generic type parameters between angle brackets (< and >) right before the function’s argument list in TypeScript.

Arrow functions can be made generic using type parameters. You can define type parameters for arrow functions in the same way you do for regular function declarations.

Syntax

const arrowFunction = <GenericType>(arg: GenericType): ReturnType => {
   // Function body
};

Example

// Arrow function with a generic type T
const identity = <T>(value: T): T => {
  return value;
};

// Using the arrow function with different types
const numberValue = identity<number>(42);
const stringValue = identity<string>("Hello, TypeScript!");

console.log(numberValue)
console.log(stringValue)

Output

42
Hello, TypeScript!

This code example has an arrow function identity with a generic type T.

The function takes an argument value of type T and returns a value of the same type T.

The example shows that we use the identity function with different types, like numbers and strings.

Making an arrow function generic in a .tsx file

In TypeScript (and in .tsx files), arrow functions can be generic using type parameters. Here’s a step-by-step guide on how to create a generic arrow function in a .tsx file:

Define the Arrow Function with Generics

const identity = <T>(arg: T): T => {
  return arg;
};

Using the Generic Arrow Function

let outputString = identity<string>("myString");

let outputNumber = identity<number>(100);

Inference in Generics

let output = identity("myString"); // string is inferred

That’s it.