What is the Syntax for Typescript Arrow Functions with Generics

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.

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!

In this code example, we have 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.

As shown in the example, we then use the identity function with different types, like numbers and strings.

That’s it.

Leave a Comment