0
0
Typescriptprogramming~5 mins

Generic function syntax in Typescript

Choose your learning style9 modes available
Introduction

Generic functions let you write one function that works with many types. This saves time and avoids repeating code.

When you want a function to work with different types of data, like numbers or strings.
When you want to keep your code flexible and reusable.
When you want to avoid writing the same function many times for different types.
When you want to keep type safety while using different data types.
When you want to create utility functions that work with any type.
Syntax
Typescript
function functionName<T>(param: T): T {
  // function body
  return param;
}

The <T> after the function name declares a generic type named T.

You can use T as a type inside the function for parameters and return values.

Examples
This function returns whatever value it receives, keeping the same type.
Typescript
function echo<T>(value: T): T {
  return value;
}
This function returns the first item from an array of any type.
Typescript
function firstElement<T>(arr: T[]): T {
  return arr[0];
}
This function puts any item inside an array and returns it.
Typescript
function wrapInArray<T>(item: T): T[] {
  return [item];
}
Sample Program

This program defines a generic function identity that returns the input value. It is called with a number and a string, showing it works with both types.

Typescript
function identity<T>(arg: T): T {
  return arg;
}

const num = identity<number>(42);
const str = identity<string>("hello");

console.log(num);
console.log(str);
OutputSuccess
Important Notes

You can use any name instead of T, but T is common and means 'Type'.

TypeScript can often guess the type, so you can call identity(42) without <number>.

Generic functions help keep your code safe and flexible at the same time.

Summary

Generic functions let you write one function for many types.

Use <T> to declare a generic type.

They keep your code reusable and type-safe.