Working with TypeScript’s Generics

24 Jun 2023 Balmiki Mandal 0 Typescript

Working with TypeScript’s Generics

Generics is one of the most powerful features of TypeScript. It allows us to create components that can work with any type of data. By using generics, we can create more generic and reusable code. In this tutorial, we will learn how to use generics in TypeScript and how it can help us write better code.

What Are Generics?

Generics are a way of defining a data type or a set of related data types. They allow us to write reusable and flexible code by specifying the type inside angle brackets <>.For example, the following code defines a generic type called T:

    type T = 

Now, if we want to create a generic function, we can use T along with the function parameters. For example, the following code defines a generic function called myFunc:

    function myFunc(param: T): T {
        return param;
    }

We can now use this generic type in any of our functions that require parameters of a certain type. For example, let’s say we have an array of string values and we need to find the longest one. We can use myFunc to do this:

    const strings = ['foo', 'bar', 'baz'];

    const longestString = myFunc(strings);

This code finds the longest string in the array and returns it as a value of type string.

Using Generic Types

We can also use generic types when creating objects. In this case, the generic type is used to specify the type of the object’s properties. For example, let’s say we want to create an object that has a name and an age property. We can define it like this:

    type Person = {
        name: string;
        age: number;
    }

Now, we can create a generic type for an object with a Person property type:

    type PersonObject = {
        person: T;
    }

This generic type allows us to create an object with any type of Person property. For example, we can create an object with a Person type like this:

    const personObject: PersonObject = {
        person: {
            name: 'John',
            age: 25,
        }
    }

We can also make our generic type more flexible by allowing it to accept multiple Person types:

    type PersonObject = {
        person?: T;
    }

Now, we can create an object that accepts a Person, null, or undefined Person type:

    const personObject: PersonObject = {
        person: null // or undefined or a valid Person
    }

Conclusion

Generics is a powerful feature of TypeScript that allows us to create more generic and reusable code. We can use generics to define the type of object properties, function parameters, and more. In this tutorial, we learned how to use generics in TypeScript and how they can help us write better code.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.