DEV Community

Shagun Mistry
Shagun Mistry

Posted on

Write Reusable Code with Typescript Generics

Generics are a powerful tool for creating reusable and flexible code components. They allow you to write code that can work with different data types without sacrificing type safety.

Imagine you're building a function to sort an array. You'd love to write it once and use it for arrays of numbers, strings, or even custom objects. That's where generics come in!

Here's a basic example:

function sortArray<T>(array: T[], compareFn: (a: T, b: T) => number): T[] {
  return array.sort(compareFn);
}

const numbers = [3, 1, 4, 1, 5];
const sortedNumbers = sortArray(numbers, (a, b) => a - b); 

const names = ["Alice", "Bob", "Charlie"];
const sortedNames = sortArray(names, (a, b) => a.localeCompare(b));

console.log(sortedNumbers); // [1, 1, 3, 4, 5]
console.log(sortedNames); // ["Alice", "Bob", "Charlie"]
Enter fullscreen mode Exit fullscreen mode

In this example, sortArray is a generic function. The <T> part defines a type parameter called T.

This parameter represents a placeholder for any data type. When we call sortArray, we specify the actual type for T (like number or string).

This way, sortArray becomes a reusable function that works with various data types, thanks to the magic of generics!

Key Benefits of Generics:

  • Flexibility: Generics allow you to write code once and use it with different data types.
  • Type Safety: TypeScript still ensures type correctness even with generic code, preventing unexpected runtime errors.
  • Code Reusability: Generics promote writing more reusable components, which means less code duplication and easier maintenance.

I hope this quick introduction to Typescript Generics helps you write better code!

If it does, please subscribe to get more content like this!

Top comments (0)