Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Generics in TypeScript

Generics

The type checking in TypeScript ensure that variables in our code can only have specific types of values assigned to them.

This way we can avoid a lot of mistakes while writing code because IDE/framework tell us wrong type before performing operation. This makes type checking one of the best features of TypeScript.

In this post we will focus what is generics and how to use generics in typescript.

Simple Definition

Generics is nothing but a parameterized type, which can be used in a verity scenario with type safety.

Why we need generics?

Important feature of generics is it creates reusable components that can work over a variety of types rather than one. This allows users to consume these components and use with their own types.

Check following example:

Following examples there are two redundant methods used to return user data

Return user number

function userData(arg: number): number {
    var test;
    if (typeof arg === "number") {
        // return employee id
        test = arg;
        return test;
    }
}

Return user name

function userData(arg:string): string {
    var test: string;
    if (typeof arg === "string") {
        //return employee name
        test = arg;
        return test;
    }
 
    return test;
}

 

How to create reusable method?

Using Any

Fowling method is reusable for employee id and username both types

function userDataReusable(arg: any): any {
    var test;
    if (typeof arg === "number") {
        // return user unique number
        test = arg;
        return test;
    } else if (typeof arg === "string") {
 
        //return username
        test = arg;
        return test;
    }
    return test;
}

 

Using generic

Fowling method is reusable for employee id and username both types

function userReusableWithGenerics<T>(arg: T): T {
    var test;
    if (typeof arg === "number") {
        // return user unique number
        test = arg;
        return test;
    } else if (typeof arg === "string") {
 
        //return username
        test = arg;
        return test;
    }
    return test;
}

 

Array example with generics

Following example has an argument arg which is an array of Ts, and returns an array of T

function arrayExample<T>(arg: Array<T>): Array<T> {
    console.log(arg.length);  // Array has a .length, so no more error
    return arg;
}