0
0
Typescriptprogramming~5 mins

Why generics are needed in Typescript

Choose your learning style9 modes available
Introduction

Generics let us write flexible code that works with many types without repeating ourselves. They help keep code safe and clear.

When you want a function to work with different types of data, like numbers or strings.
When creating reusable components that can handle various data types.
When you want to avoid writing the same code for different types.
When you want to keep type safety but still be flexible.
When building libraries or tools that others will use with different data.
Syntax
Typescript
function identity<T>(arg: T): T {
  return arg;
}

T is a placeholder for any type you provide later.

You use <T> after the function name to declare a generic type.

Examples
This function returns whatever you give it, keeping the type.
Typescript
function identity<T>(arg: T): T {
  return arg;
}
Here, we tell the function to use string as the type.
Typescript
const output = identity<string>("hello");
This function works with arrays of any type and logs their length.
Typescript
function loggingIdentity<T>(arg: T[]): T[] {
  console.log(arg.length);
  return arg;
}
Sample Program

This program shows how the generic function identity returns the same value and type you give it.

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

Generics help avoid using any, which loses type safety.

You can use multiple generic types like <T, U> if needed.

Summary

Generics make code reusable and type-safe.

They let you write one function or component for many types.

Using generics helps catch errors early and keeps code clear.