VOOZH about

URL: https://dev.to/jefersoneiji/understanding-generics-in-typescript-for-improved-code-reusability-4279

⇱ Understanding Generics in TypeScript for Improved Code Reusability - DEV Community


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

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" };

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.