TypeScript Generics

TypeScript tutorial

🧬 TypeScript Generics

TypeScript Generics allow you to write reusable, type-safe code that works with multiple types instead of a single one.

📌 Think of generics as placeholders for types


1️⃣ Why Generics?

Without generics, you lose type safety:

function identity(value: any): any {
return value;
}

With generics ✅:

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

2️⃣ Generic Functions

function getFirst<T>(arr: T[]): T {
return arr[0];
}
getFirst<number>([1, 2, 3]);
getFirst<string>([“A”, “B”, “C”]);

✔ Type-safe
✔ Reusable


3️⃣ Type Inference with Generics

You usually don’t need to specify the type.

getFirst([10, 20, 30]); // T = number
getFirst(["x", "y", "z"]); // T = string

4️⃣ Generic Arrow Functions

const reverse = <T>(items: T[]): T[] => {
return items.reverse();
};

5️⃣ Generic Interfaces

interface ApiResponse<T> {
data: T;
success: boolean;
}
let res1: ApiResponse<string> = {
data: “OK”,
success: true
};let res2: ApiResponse<number[]> = {
data: [1, 2, 3],
success: true
};

6️⃣ Generic Classes

class Box<T> {
constructor(public value: T) {}
}
let box1 = new Box<number>(100);
let box2 = new Box<string>(“Hello”);

7️⃣ Multiple Generic Types

function pair<K, V>(key: K, value: V): [K, V] {
return [key, value];
}
pair<number, string>(1, “One”);

8️⃣ Generic Constraints (extends)

Restrict the types that can be used.

function lengthOf<T extends { length: number }>(item: T): number {
return item.length;
}
lengthOf(“Hello”);
lengthOf([1, 2, 3]);

❌ Error:

lengthOf(10);

9️⃣ keyof with Generics

function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
getProperty({ name: “Sanjit”, age: 25 }, “name”);

🔟 Generic Default Types

interface Response<T = string> {
data: T;
}
let r: Response = { data: “Default type” };

🔑 Generics Summary

Feature Example
Function <T>(value: T)
Class class Box<T>
Interface interface Api<T>
Multiple <K, V>
Constraint extends
keyof K extends keyof T

⭐ Best Practices

✔ Use generics to avoid any
✔ Keep generic names short (T, K, V)
✔ Add constraints for safety
✔ Don’t over-complicate generics

You may also like...