0
0
Typescriptprogramming~5 mins

Generic arrow functions in Typescript

Choose your learning style9 modes available
Introduction

Generic arrow functions let you write flexible functions that work with many types without repeating code.

When you want a function to work with different data types like numbers or strings.
When you want to keep your code reusable and avoid writing the same function for each type.
When you want to create utility functions that handle various types safely.
When you want to keep type safety but still be flexible with input types.
Syntax
Typescript
const functionName = <T>(param: T): T => {
  // function body
  return param;
};

The <T> declares a generic type parameter named T.

You can use any letter or name instead of T, but T is common.

Examples
This function returns whatever value it receives, keeping the same type.
Typescript
const identity = <T>(value: T): T => value;
This function puts the input item inside an array of the same type.
Typescript
const wrapInArray = <T>(item: T): T[] => [item];
This function returns the first element of an array or undefined if empty.
Typescript
const getFirst = <T>(arr: T[]): T | undefined => arr[0];
Sample Program

This program shows a generic arrow function echo that returns the input as is. It works with both numbers and strings.

Typescript
const echo = <T>(input: T): T => input;

const numberEcho = echo(123);
const stringEcho = echo("hello");

console.log(numberEcho);
console.log(stringEcho);
OutputSuccess
Important Notes

Generic functions help keep your code DRY (Don't Repeat Yourself).

TypeScript checks that you use the same type for input and output when using generics.

Summary

Generic arrow functions let you write one function for many types.

Use <T> to declare a generic type parameter.

This keeps your code flexible and type-safe.