TypeScript Generics
TypeScript Generics — Build Flexible and Reusable Code
Generics allow you to create templates for code — like filling in blanks that get replaced based on how your function, class, or type is used.
Think of it like a blueprint with a placeholder type, making your code versatile while keeping it type-safe.
Why Use Generics?
Instead of writing multiple versions of a function or class for different types (like number, string, boolean, etc.), you can use one generic version that adapts based on the input.
Basic Generic Function
function wrapInArray<T>(item: T): T[] {
return [item];
}
const numArray = wrapInArray(10);
const textArray = wrapInArray("hello");
- T here is a placeholder for the actual type.
- It changes depending on the argument passed.
Generic in Interfaces
Generics also work with interfaces when you're crafting reusable shapes:
interface Box<U> {
content: U;
}
const stringBox: Box<string> = { content: "Books" };
Const numberBox: Box<number> = { content: 123 };
It helps you design reusable data containers for anything.
Generic Classes
class Container<T> {
private item: T;
constructor(item: T) {
this.item = item;
}
get(): T {
return this.item;
}
}
Const stringContainer = new Container("Generics");
console.log(stringContainer.get());
This class can hold any type of data and still maintain type integrity.
Generic Constraints
You can also limit what types are allowed with constraints:
function getLength<T extends { length: number }>(arg: T): number {
return arg.length;
}
getLength("hello");
getLength([1, 2, 3]);
extends ensures that only types with a length property are valid.
Multiple Generics
function pair<A, B>(first: A, second: B): [A, B] {
return [first, second];
}
const result = pair("age", 25);
You can use more than one generic side by side to build pairings or mappings.
Wrap-Up
| Benefit | What it Means |
|---|---|
| Type Flexibility | Reuse with different data types |
| Type Safety | Errors are caught during development |
| Cleaner Code | No need for multiple overloads |
Prefer Learning by Watching?
Watch these YouTube tutorials to understand TYPESCRIPT Tutorial visually:
What You'll Learn:
- 📌 TypeScript Tutorial #18 - Generics
- 📌 TypeScript Generics Explained | Typescript Generics Tutorial | TypeScript Tutorial | Simplilearn