How to Use Generic Arrow Functions in TypeScript?

As a developer, I once faced a challenge while working on a project for a logistics company in New York. We needed to create a reusable function to handle different types of data, from customer details to shipment information. Using generic arrow functions in TypeScript, we can achieve this. In this tutorial, I will explain how to use generic arrow functions in TypeScript with examples.

To define a generic arrow function in TypeScript, you place the type parameter before the function’s parameters. For example, const identity = <T>(value: T): T => value; creates a function that takes a value of any type T and returns a value of the same type.

What Are Generic Arrow Functions in TypeScript?

Generic arrow functions in TypeScript allow you to create functions that can work with any data type. This is achieved by defining a type variable that acts as a placeholder for the actual type that will be used when the function is called. This approach enhances code flexibility and reusability, making it easier to manage different data types without duplicating code.

Why Use Generic Arrow Functions in TypeScript?

Here are a few useful reasons why we use generic arrow functions in TypeScript.

  1. Type Safety: Ensures that the data types are consistent and errors are caught at compile time.
  2. Reusability: Write once, use anywhere. Generic functions can handle various data types without modification.
  3. Maintainability: Reduces code duplication and makes the codebase easier to manage.

Read How to Return Multiple Values in TypeScript?

Define a TypeScript Generic Arrow Function

To define a generic arrow function in TypeScript, you place the type variable before the function’s parameters. Here’s a simple example:

const identity = <T>(value: T): T => value;

In this example, <T> is the generic type parameter. The function identity takes a value of type T and returns a value of the same type.

Let me show you a simple example of the generic arrow function in TypeScript.

This function returns the value it receives, regardless of the type.

const identity = <T>(value: T): T => value;

console.log(identity<number>(42)); // Output: 42
console.log(identity<string>("Hello, TypeScript!")); // Output: Hello, TypeScript!

The identity function is a generic arrow function where <T> is the type parameter. The function takes a single parameter value of type T and returns a value of the same type. This ensures that the function can handle any type of input and return it without modification. In the examples, the function is called with a number and a string, as you can see above.

I executed the above code using VS code, and you can see the exact output in the screenshot below;

typescript generic arrow function

Check out Get Return Type of a Function in TypeScript

TypeScript Generic Arrow Function Examples

Now, let me show you some examples of generic arrow functions in TypeScipt.

Example 1: Logging Data

Let’s consider a real-world scenario where we need to handle customer data and shipment details in a logistics application. We can use generic arrow functions to create a reusable function for logging different types of data.

interface Customer {
    id: number;
    name: string;
    email: string;
}

interface Shipment {
    trackingNumber: string;
    destination: string;
    weight: number;
}

const logData = <T>(data: T): void => {
    console.log(data);
};

const customer: Customer = {
    id: 101,
    name: "John Doe",
    email: "john.doe@example.com"
};

const shipment: Shipment = {
    trackingNumber: "1Z999AA10123456784",
    destination: "Los Angeles, CA",
    weight: 25.5
};

logData(customer); // Logs customer data
logData(shipment); // Logs shipment data

In this example, the logData function can handle both Customer and Shipment data types, thanks to the generic type parameter <T>.

Example 2: Swapping Tuple Values

Another powerful use of generic arrow functions is to swap values in a tuple. This can be particularly useful in scenarios where you need to manipulate pairs of data.

const swap = <T, U>(tuple: [T, U]): [U, T] => {
    return [tuple[1], tuple[0]];
};

const coordinates: [number, string] = [40.7128, "New York City"];
const swappedCoordinates = swap(coordinates); // ["New York City", 40.7128]

console.log(swappedCoordinates);

In this example, the swap function takes a tuple of two different types and returns a new tuple with the values swapped.

Here is the exact output in the screenshot below:

TypeScript Generic Arrow Function Examples

Check out How to Use Default Function Parameters in TypeScript?

Example 3: Key-Value Pair

This function creates a key-value pair object from two input values.

const createPair = <K, V>(key: K, value: V): { key: K, value: V } => ({ key, value });

console.log(createPair<string, number>("age", 30)); // Output: { key: "age", value: 30 }
console.log(createPair<number, string>(1, "one")); // Output: { key: 1, value: "one" }

The createPair function is a generic arrow function with two type parameters, <K, V>. It takes two parameters: key of type K and value of type V, and returns an object with properties key and value. This function is useful for creating objects that represent key-value pairs. It can handle various types for both the key and the value. The examples explain how the function is used to create key-value pairs with different types.

Example 4: Array Wrapper

This function takes a single value and returns it wrapped in an array.

const wrapInArray = <T>(value: T): T[] => [value];

console.log(wrapInArray<number>(10)); // Output: [10]
console.log(wrapInArray<string>("TypeScript")); // Output: ["TypeScript"]

The wrapInArray function is another generic arrow function where <T> is the type parameter. It takes a single parameter value of type T and returns an array containing that value. This function ensures that a single value is always returned as an array, regardless of its type. The examples show the function being used with a number and a string.

Conclusion

Generic arrow functions in TypeScript are useful for writing flexible, reusable, and type-safe code. In this tutorial, I explained how to work with the generic arrow function in TypeScript with a few examples.

You may also like: