Exploring Generics in TypeScript
Generics are a powerful feature in TypeScript that enables the creation of reusable and type-safe components. This guide dives deep into generics and demonstrates their practical applications.
What Are Generics?
Generics allow a component (such as a function, class, or interface) to work with various types without losing type safety. They are especially useful when creating reusable and flexible code.
Syntax:
function identity<T>(arg: T): T {
return arg;
}
Here, T
is a type variable representing the type passed to the function.
Benefits of Generics
- Type Safety: Avoids using
any
while maintaining flexibility.
- Code Reusability: Enables the use of the same code for multiple types.
- Readability: Clarifies the intent of the code.
Using Generics in Functions
Example 1: Generic Identity Function
function identity<T>(arg: T): T {
return arg;
}
const num = identity<number>(42);
const str = identity<string>("Hello");
console.log(num, str);
Example 2: Working with Arrays
function getFirstElement<T>(arr: T[]): T {
return arr[0];
}
const firstNumber = getFirstElement([1, 2, 3]);
const firstString = getFirstElement(["a", "b", "c"]);
console.log(firstNumber, firstString); // Output: 1, "a"
Generics in Interfaces
Generics can define the shape of a reusable interface.
interface Box<T> {
content: T;
}
const stringBox: Box<string> = { content: "Hello, Generics!" };
const numberBox: Box<number> = { content: 123 };
Generics in Classes
Generics can also be used in class definitions to make them reusable.
class GenericNumber<T> {
value: T;
constructor(value: T) {
this.value = value;
}
multiply(factor: T): string {
return `Value is \${this.value} and factor is \${factor}`;
}
}
const numInstance = new GenericNumber<number>(10);
console.log(numInstance.multiply(2)); // Output: Value is 10 and factor is 2
Constraints with Generics
Constraints limit the types that can be passed to a generic.
function logLength<T extends { length: number }>(item: T): void {
console.log(item.length);
}
logLength("Hello"); // Valid . Output: 5
logLength([1, 2, 3]); // Valid. Output: 3
// logLength(42); // Error
Key Points
- Generics provide flexibility while maintaining type safety.
- They work with functions, classes, interfaces, and more.
- Constraints ensure generics are used appropriately.
Next Steps
The next article will focus on comparing Type and Interface in TypeScript and understanding their differences in detail.
Explore generics to create reusable, type-safe TypeScript components!