BugFree.dev
  • Home
  • Articles
  • About Us
  • Contact Us

Main Menu

  • Home
  • Articles
  • About Us
  • Contact Us
BugFree.dev

Code with Confidence

Quick Links

  • Advertise with us
  • About Us
  • Contact Us

Legal Stuff

  • Privacy Notice
  • Cookie Policy
  • Terms Of Use

© Copyright 2025 BugFree.dev

Exploring Generics in TypeScript

Generics are a powerful feature in TypeScript that enables the creation of reusable and type-safe components. This guide dives deep into generics and demonstrates their practical applications.


What Are Generics?

Generics allow a component (such as a function, class, or interface) to work with various types without losing type safety. They are especially useful when creating reusable and flexible code.

Syntax:

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

Here, T is a type variable representing the type passed to the function.


Benefits of Generics

  1. Type Safety: Avoids using any while maintaining flexibility.
  2. Code Reusability: Enables the use of the same code for multiple types.
  3. Readability: Clarifies the intent of the code.

Using Generics in Functions

Example 1: Generic Identity Function

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

const num = identity<number>(42);
const str = identity<string>("Hello");
console.log(num, str);

Example 2: Working with Arrays

function getFirstElement<T>(arr: T[]): T {
    return arr[0];
}

const firstNumber = getFirstElement([1, 2, 3]);
const firstString = getFirstElement(["a", "b", "c"]);
console.log(firstNumber, firstString); //   Output: 1, "a"

Generics in Interfaces

Generics can define the shape of a reusable interface.

interface Box<T> {
    content: T;
}

const stringBox: Box<string> = { content: "Hello, Generics!" };
const numberBox: Box<number> = { content: 123 };

Generics in Classes

Generics can also be used in class definitions to make them reusable.

class GenericNumber<T> {
    value: T;
    constructor(value: T) {
        this.value = value;
    }
    multiply(factor: T): string {
        return `Value is \${this.value} and factor is \${factor}`;
    }
}

const numInstance = new GenericNumber<number>(10);
console.log(numInstance.multiply(2)); // Output: Value is 10 and factor is 2

Constraints with Generics

Constraints limit the types that can be passed to a generic.

function logLength<T extends { length: number }>(item: T): void {
    console.log(item.length);
}

logLength("Hello"); // Valid . Output: 5
logLength([1, 2, 3]); // Valid. Output: 3
// logLength(42); // Error

Key Points

  1. Generics provide flexibility while maintaining type safety.
  2. They work with functions, classes, interfaces, and more.
  3. Constraints ensure generics are used appropriately.

Next Steps

The next article will focus on comparing Type and Interface in TypeScript and understanding their differences in detail.


Explore generics to create reusable, type-safe TypeScript components!

Topics

Related Tags

Let's Talk

Subscribe to our newsletter to be among the first to keep up with the latest updates.

Next.js Caching: unstable_cache vs. React Cache Compared

Caching plays a pivotal role in web application performance, enabling faster responses and reducing server load. Both Next.js and React offer caching mechanisms, but they serve different purposes and are used in different contexts. This article delves into the details of Next.js unstable_cache and React Cache, highlighting their differences, use cases, and examples.

Reza

01/23/20255 mins

Exploring Real-World Scenarios with TypeScript

TypeScript is not just a theoretical tool; it shines in real-world applications, providing type safety, scalability, and enhanced developer experience. This article demonstrates practical TypeScript usage in real-world scenarios, helping to solidify the concepts learned earlier.

Reza

01/15/20253 mins

Difference Between Type and Interface in TypeScript

TypeScript provides two ways to define complex types: type aliases and interfaces. Both are widely used but serve different purposes. This guide explains their differences in detail.

Reza

01/14/20252 mins

Exploring Advanced Types in TypeScript

TypeScript provides advanced type features to model complex structures and enhance type safety. This guide introduces interfaces, type aliases, and enums.

Reza

01/11/20252 mins