DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on • Originally published at dev.to

Understanding Generics in TypeScript for Improved Code Reusability

What Are Generics in TypeScript?

Generics are a feature in TypeScript that allow you to create reusable components that work with a variety of data types, rather than a single one. They enable you to write functions, interfaces, and classes that can operate with different data types while still maintaining type safety.

Why Use Generics?

  • Code Reusability: Write a function or a class once and use it for any data type.
  • Type Safety: TypeScript keeps track of the types used, avoiding runtime errors.
  • Flexibility: Functions and classes become more flexible and adaptable to changing requirements.

Example: Generic Function

Suppose you want a function to return the same argument passed to it:

function identity<T>(arg: T): T {
  return arg;
}

const num = identity(5);        // num is of type number
const str = identity("hello"); // str is of type string
Enter fullscreen mode Exit fullscreen mode

In this example, the type T is a placeholder that will be replaced with the actual type when the function is used. This means you can use identity with any data type.

Example: Generic Interface

interface Box<T> {
  value: T;
}

const numberBox: Box<number> = { value: 123 };
const stringBox: Box<string> = { value: "TypeScript" };
Enter fullscreen mode Exit fullscreen mode

Summary

Generics make your code more reusable, safer, and adaptable. They are especially useful in utility libraries, data structures, and APIs where flexibility across multiple data types is needed.

Top comments (0)