A Beginner's Guide to TypeScript Generics: Boost Your Code Flexibility
Learn how TypeScript generics can make your code more reusable and type-safe with this easy beginner-friendly tutorial.
TypeScript generics are a powerful feature that allow you to write flexible, reusable functions and classes while still preserving strong type safety. For beginners, generics might seem tricky at first, but they can significantly improve your code by making it more adaptable to different types without sacrificing type checking.
Imagine you want to create a function that returns the first element of an array. Without generics, you'd have to create a separate function for every type or lose type information. With generics, you can write one function that works for any type!
function getFirstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
const numbers = [1, 2, 3];
const firstNumber = getFirstElement(numbers); // Type is number
const strings = ['a', 'b', 'c'];
const firstString = getFirstElement(strings); // Type is stringIn the example,
Generics work well with classes too. Here's a simple generic stack class that can store any type of data:
class Stack<T> {
private items: T[] = [];
push(item: T) {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
}
const numberStack = new Stack<number>();
numberStack.push(10);
numberStack.push(20);
console.log(numberStack.pop()); // Output: 20By using generics, you ensure the stack only accepts and returns items of the specified type, improving safety and reducing bugs.
You can also constrain generics when you want to limit the types allowed. For example, to accept only objects with a "length" property:
function logLength<T extends { length: number }>(item: T): void {
console.log(`Length is: ${item.length}`);
}
logLength('hello'); // Length is: 5
logLength([1, 2, 3]); // Length is: 3
// logLength(10); // Error: number doesn't have 'length' propertyThis constraint helps avoid errors by restricting generics to compatible types.
To sum up, generics enhance your TypeScript code by: - Making functions and classes reusable with any data type - Keeping type safety intact - Avoiding code duplication - Allowing flexible but constrained typing As you practice, generics will become a natural part of your coding toolkit, helping you write cleaner and more maintainable code.
Try adding generics to your next TypeScript project to experience the benefits firsthand!