Generics is a core feature in statically-typed languages like TypeScript, enabling developers to define components, functions, or structures that can accept and enforce types passed during use. This enhances flexibility, promotes reusability, and reduces code duplication.
In this tutorial, we'll explore practical examples of TypeScript generics and learn how to use them effectively in functions, types, classes, and interfaces to improve type safety and adaptability in your code.
Prerequisites
class MyStorage<T> {private items: T[] = [];addItem(item: T): void {this.items.push(item);}getAllItems(): T[] {return this.items;}getItem(index: number): T | undefined {return this.items[index];}deleteItem(index: number): T | undefined {if (index >= 0 && index < this.items.length) {return this.items.splice(index, 1)[0];}return undefined;}}// Usageconst stringStorage = new MyStorage<string>();stringStorage.addItem("Hello");stringStorage.addItem("World");const numberStorage = new MyStorage<number>();numberStorage.addItem(42);numberStorage.addItem(100);
About the author
NAB, Lead Engineer
I'm Vu, a Lead Engineer at NAB (National Australia Bank). I started on Home Lending products and now lead a team building products for HICAPS, Australia's largest point of sale claiming service for private health insurance. Before NAB, I worked at startups and across a range of teams and stacks.
Upskills is where I share practical, real-world knowledge to help others build and maintain projects better. Beyond tutorials, more content is coming: project showcases, interview prep, and AI tools as resources for your learning journey. I'm excited to share what I've learned and keep learning together as we build cool things.
Practical web development deep-dives, every other week, written by an engineer who ships them. No fluff, no hot takes.
We respect your privacy. Unsubscribe anytime.