DEV Community

Cover image for Understanding Generics in TypeScript: The Ultimate Guide to Reusable Code
Nahidul Islam
Nahidul Islam

Posted on • Originally published at nahidulislam11.Medium

Understanding Generics in TypeScript: The Ultimate Guide to Reusable Code

πŸš€ What Are Generics in TypeScript?

When developing applications, we often need flexibility while maintaining type safety. TypeScript’s Generics solve this challenge by allowing us to create reusable components that can work with multiple data types.

In this guide, we’ll break down generics step by step, ensuring you fully understand how to use them efficiently.

🎯 Why Should You Learn Generics?

Without generics, you would need separate functions for different data types. For example:

function returnString(value: string): string {
  return value;
}

function returnNumber(value: number): number {
  return value;
}
Enter fullscreen mode Exit fullscreen mode

This approach leads to redundant code. Generics solve this problem by creating a single function that works for all types.

πŸ† Understanding Generics with a Simple Example

Generics use a placeholder type, such as <T>, allowing a function to handle various data types dynamically.

function returnValue<T>(value: T): T {
  return value;
}
Enter fullscreen mode Exit fullscreen mode

Now, this function works for any type:

console.log(returnValue<string>("Hello Generics!"));  // "Hello Generics!"
console.log(returnValue<number>(123));               // 123
console.log(returnValue<boolean>(true));             // true
console.log(returnValue<object>({ name: "TypeScript" })); // { name: "TypeScript" }
Enter fullscreen mode Exit fullscreen mode

This is the power of generics β€” one function that adapts to different types while maintaining type safety.

πŸ—οΈ Applying Generics in Classes

If you’re working with data storage, you can use generics in a class to make it flexible yet secure:

class Storage<T> {
  private item: T;

  setItem(value: T) {
    this.item = value;
  }

  getItem(): T {
    return this.item;
  }
}

// Using the class with different types
const stringStorage = new Storage<string>();
stringStorage.setItem("Understanding Generics is fun!");
console.log(stringStorage.getItem()); // "Understanding Generics is fun!"

const numberStorage = new Storage<number>();
numberStorage.setItem(42);
console.log(numberStorage.getItem()); // 42
Enter fullscreen mode Exit fullscreen mode

Since Generics preserve type integrity, you won’t accidentally store numbers in a string container.

πŸ”— Generics in Interfaces for Flexible Object Type

You can apply generics in interfaces to create highly adaptable structures.

interface User<T> {
  id: number;
  data: T;
}

const user1: User<string> = { id: 1, data: "Admin" };
const user2: User<number[]> = { id: 2, data: [10, 20, 30] };

console.log(user1); // { id: 1, data: "Admin" }
console.log(user2); // { id: 2, data: [10, 20, 30] }
Enter fullscreen mode Exit fullscreen mode

Here, data can be any type, making the interface highly reusable.

πŸ”₯ Adding Constraints to Generic

If you want **restrictions **on the generic type, use extends:

function getLength<T extends { length: number }>(item: T): number {
  return item.length;
}

console.log(getLength("Understanding Generics"));  // βœ… Works (strings have `.length`)
console.log(getLength([1, 2, 3]));                 // βœ… Works (arrays have `.length`)
console.log(getLength({ length: 10 }));            // βœ… Works (objects with length are allowed)
Enter fullscreen mode Exit fullscreen mode

Here, T extends { length: number } ensures that only values with a .length property are accepted.

πŸš€ Benefits of Generics in TypeScript

  1. Write Less Code β€” One function or class for multiple types.
  2. Increase Flexibility β€” Works with different data types while enforcing type safety.
  3. Improve Maintainability β€” No need to refactor when adding new types.
  4. Future-Proof Applications β€” Generics scale easily as your codebase grows. Generics are essential in TypeScript and make your code efficient, clean, and reusable.

🎯 Final Challenge: Try Generics Yourself

Want to test your understanding of generics? Try writing a generic function that adds two values β€” it should work for both numbers and strings! Drop your solution in the comments below.

πŸ™‹πŸ»β€β™‚οΈ Explore my portfolio ✨
This is where innovation meets expertise ✨ β€” a carefully crafted showcase of my professional journey. Dive into a world where each project tells its own story of challenges conquered πŸ† and solutions crafted πŸ› οΈ. While my portfolio demonstrates technical prowess πŸ’», it also reflects my passion for pushing boundaries πŸš€ and thinking beyond conventional limits 🌌. Ready to connect? 🀝 Find me on LinkedIn for the full story of my professional adventure, and let’s explore potential collaborations. Together, we might just create something extraordinary 🌟.

Top comments (0)