DEV Community

Shagun Mistry
Shagun Mistry

Posted on

3 1

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!

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more