DEV Community

Anil K Tiwari
Anil K Tiwari

Posted on

Demystifying TypeScript Generics with Simple Examples

TypeScript Generics can seem daunting at first, but they are a powerful tool for creating flexible and type-safe code. In this article, we'll explore Generics through easy-to-understand examples, breaking down the concepts step by step.

What Are Generics?

Generics in TypeScript allow you to write code that can work with different data types while still maintaining type safety. Think of them as placeholders for types that you specify when you use them.

Generic Functions

Let's start with the basics by looking at generic functions:

function echo<T>(arg: T): T {
    return arg;
}
Enter fullscreen mode Exit fullscreen mode

Here, echo is a generic function. The <T> part inside the parentheses declares that T is a type parameter. It's like saying, "I'll tell you the type later."

Now, when you call echo and provide an argument, TypeScriptfigures out the type based on what you pass:

let result = echo("Hello, TypeScript"); // result is of type 'string'
Enter fullscreen mode Exit fullscreen mode

In this case, result is automatically recognized as a string because we passed a string as an argument.

Generic Classes

Generics aren't limited to functions; you can also use them with classes. Consider a simple example of a generic class Box:

class Box<T> {
    private value: T;

    constructor(value: T) {
        this.value = value;
    }

    getValue(): T {
        return this.value;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this class, T is a type parameter that represents the type of the value property. When you create a Box instance, you specify the type it will hold:

let numberBox = new Box<number>(42); // numberBox can only hold numbers
let stringBox = new Box<string>("Hello, TypeScript"); // stringBox can only hold strings
Enter fullscreen mode Exit fullscreen mode

TypeScript ensures that you can't mix types within a Box. Trying to do so would result in a compile-time error.

Real-World Applications

Now that you've grasped the basics, let's see where Generics can be valuable:

1.Array Functions: Many array methods like map, filter, and reduce use Generics under the hood to work with different element types.

  1. Promises: Promises can return various types of values, and Generics help define the expected return type when using Promise<T>.

  2. React Components: Creating reusable components that can work with different data types as props.

  3. API Requests: When fetching data from an API, Generics can specify the expected shape of the response data.

Conclusion

Generics might appear complex at first glance, but they're a valuable tool for writing versatile and type-safe code. By using them, you can create functions, classes, and data structures that adapt to different types while catching type errors early in the development process. As you become more comfortable with Generics, you'll find them indispensable in building robust and maintainable TypeScript applications.

Top comments (0)