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

Enums in TypeScript

Enums 

In computer programming, an enumerated type (also called enumeration, enum, or factor in the R programming language, and a categorical variable in statistics) is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type(reference wikipedia.org).

Enum allows us to create set of named constants, common use is we can create distinct cases. TypeScript provides both numeric and string-based enums.

We can create three types of enum  in typescript following examples will explain in details , how to create enums.


1. Numeric enums

We will start with numeric enums, an enum can be defined using the enum keyword.

Enum Visibility
    {
        None=1,
        Hidden,
        Visible
    };

Above, we have a numeric enum where Up is initialized with 1. All the following members are auto-incremented from that point on. In other words, Visibility.None has the value 1, Hidden has 2, Visible has 3.

enum Visibility
{
    None,
    Hidden,
    Visible
};

Here, None would have the value 0Hidden would have 1, etc. This auto-incrementing behavior is useful for cases where we might not care about the member values themselves, but do care that each value is distinct from other values in the same enum.

How to use it:

Using an enum is simple: just access any member as a property off the enum itself, and declare types using the name of the enum, check following example where we used enum to set text display mode.

Example:

function
setVisibiity(recipient: string, message: Visibility): void {
    // ...
}

setVisibiity("Aditya Balaji Kendre", Visibility.Visible)


2. String enums

In a string enum, each member must be constant-initialized with a string literal, or with another string enum member.

How to use it:

function
SetUserFevColor(recipient: string, userColorChoice: Colors): void {
    // ...some typescript custom code
}
 
SetUserFevColor("Ajay Balaji Kendre", Colors.Green);
 


3. Heterogeneous enums

Technically enums can be mixed with string and numeric members,but its recommended to avoid Heterogeneous enums except must require case.

Example:

enum
UpdatedData  {
    No = 0,
    Yes="YES"
}

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