Member-only story
TypeScript: What Are Generics ?
Generics in TypeScript are a powerful feature that allows developers to create reusable, flexible, and type-safe components. They help ensure that functions, classes, and interfaces work with multiple types while maintaining strong type checking.
Let’s dive into what generics are and why they are so useful! 🔥
What Are Generics in TypeScript?
Generics allow us to create dynamic, reusable code by defining a placeholder type that gets replaced with an actual type when the function, class, or interface is used.
Syntax of Generics:-
function identity<T>(value: T): T {
return value;
}
Here, T
is a generic type parameter that acts as a placeholder. When we call identity()
, TypeScript infers the type automatically or we can explicitly pass a type.
Example Usage
console.log(identity<number>(10)); // ✅ Output: 10
console.log(identity<string>("Hello")); // ✅ Output: "Hello"
Benefit: The function now works with any type while preserving type safety.
1️⃣ Generics with Functions
Generics help functions accept and return values of the same type dynamically.
Example: Generic Function
function getFirstElement<T>(arr: T[]): T {
return arr[0];
}
console.log(getFirstElement<number>([1, 2, 3])); // ✅ Output: 1
console.log(getFirstElement<string>(["Alice", "Bob"]))…