TypeScript Generic Anonymous Functions

Generics in TypeScript help to create reusable and type-safe code. Here, I will explain the concept of generic anonymous functions in TypeScript. In this tutorial, I will explain how to master TypeScript generic anonymous functions.

What are Generics in TypeScript?

Generics in TypeScript allow you to create components that can work with a variety of data types while maintaining type safety. They are particularly useful for creating functions, classes, and interfaces that need to operate on multiple types of data without sacrificing type safety.

TypeScript Anonymous Functions

Anonymous functions, also known as function expressions, are functions that are not bound to an identifier. They are often used as arguments to other functions or as immediately invoked function expressions (IIFEs).

TypeScript Generic Anonymous Functions

Combining generics with anonymous functions can significantly enhance the flexibility and reusability of your code. Let me show you how to work with TypeScript generic anonymous functions.

Check out How to Use TypeScript Optional Function Parameters?

Example 1: Generic Anonymous Function for Data Transformation

Consider a scenario where you need to transform data from various sources. Using a generic anonymous function, you can create a flexible transformer function.

type Transformer<T> = (input: T) => T;

const transformData = <T>(data: T[], transformer: Transformer<T>): T[] => {
  return data.map(transformer);
};

// Example usage
const numbers = [1, 2, 3, 4];
const double = (num: number): number => num * 2;

const doubledNumbers = transformData(numbers, double);
console.log(doubledNumbers); // Output: [2, 4, 6, 8]

In this example, transformData is a generic anonymous function that takes an array of type T and a transformer function. This setup allows you to apply any transformation to the data, maintaining type safety.

Here is the exact output in the screenshot below:

TypeScript Generic Anonymous Functions

Read How to Specify Return Type in TypeScript Arrow Functions?

Example 2: Generic Anonymous Function for API Responses

Imagine you are working with API responses that return different types of data. You can use a generic anonymous function to handle these responses uniformly. Here is the complete TypeScript code.

type ApiResponse<T> = {
  data: T;
  status: number;
};

const handleApiResponse = <T>(response: ApiResponse<T>): T => {
  if (response.status === 200) {
    return response.data;
  } else {
    throw new Error("API Error");
  }
};

// Example usage
const userResponse = {
  data: { name: "John Doe", age: 30 },
  status: 200,
};

const userData = handleApiResponse(userResponse);
console.log(userData); // Output: { name: "John Doe", age: 30 }

Here, handleApiResponse is a generic anonymous function that processes API responses. It ensures that the response data is correctly typed and only returned if the status is 200.

Read How to Return Multiple Values in TypeScript?

Example 3: Generic Anonymous Function for Form Handling

In web development, handling form data is a common task. A generic anonymous function can help manage form data efficiently.

Here is the complete code.

type FormData<T> = {
  [key: string]: T;
};

const processFormData = <T>(data: FormData<T>, callback: (value: T) => void): void => {
  for (const key in data) {
    if (data.hasOwnProperty(key)) {
      callback(data[key]);
    }
  }
};

// Example usage
const userFormData = {
  firstName: "Alice",
  lastName: "Johnson",
  age: 25,
};

processFormData(userFormData, (value) => {
  console.log(value);
});
// Output:
// Alice
// Johnson
// 25

In this example, processFormData is a generic anonymous function that processes form data and applies a callback to each form field. This approach ensures that the form handling logic is reusable and type-safe.

Conclusion

In this tutorial, I explained how to work with TypeScript generic anonymous functions with some examples. By using generics, you can create functions that work with various data types while maintaining type safety.