Thursday, September 28, 2023

TypeScript Part 11(Tuple, Enum,Never)

Tuple

It is a new data type called Tuple. It can contains values of two different data types.

Example 
var empId: number = 1;
var empName: string = "Uday";        

// Using Tuple type variable we can combine above two variables into a single one as 
var employee: [number, string] = [1, "Uday"];
Tuple can include multiple data types as well. 

Example
var user: [number, string, boolean, number, string];// declare tuple variable
user = [1, "Uday", true, 20, "Admin"];// initialize tuple variable

Tuple Array
Example

var employee: [number, string][];
employee = [[1, "Uday"], [2, "Kumar"], [3, "Kittu"]];

How to access Tuple Elements
var employee: [number, string] = [1, "Uday"];
employee[0]; // returns 1
employee[1]; // returns "Uday"

Example

var user: [number, string, boolean, number, string];// declare tuple variable
user = [1, "Uday", true, 20, "Admin"]
console.log(user[0]);
console.log(user[1]);
console.log(user[2]);
console.log(user[3]);

Output










Add Elements to Tuple
var employee: [number, string] = [1, "Uday"];
employee.push(2, "Kumar"); 
console.log(employee); //Output: [1, 'Uday', 2, 'Kumar']

Example

var user: [number, string] = [1, "Uday"];
user.push(2, "Kumar");
console.log(employee);
console.log(user[0]);
console.log(user[1]);



Enum:
It allows us to declare the named constants
three types of enums:

1 Numeric Enum
Numeric enums are number-based enums i.e. they store string values as numbers.

export enum AddressDetails{
    Name,
    Address,
    State
}

In the above example, we have an enum named AddressDetails. The enum has four values: Name, Address, State. Here, enum values start from zero and increment by 1 for each member. It would be represented as:

Name= 0
Address= 1
State= 2

Enums are always assigned numeric values when they are stored. 
The first value will be 0, while the other are incremented by 1.

We also have the option to initialize the first numeric value ourselves.
enum PaperMedia {
  Newspaper = 1,
  Newsletter,
  Magazine,
  Book
}


We can also assign in the sequential order as well
enum PaperMedia {
    Newspaper = 1,
    Newsletter = 5,
    Magazine = 5,
    Book = 10
}

The enum can be used as a function parameter or return type as shown below

Example

enum Actors {
    TollyWood=1,
    BollyWood,
    KollyWood,
    SandalWood
}

function getActorDetails(type: string): Actors {
    if (  type === 'PawanKalyan' || type === 'MaheshBabu') {
        return Actors.TollyWood;
    }
 }

let msg: Actors = getActorDetails('PawanKalyan'); // returns TollyWood
console.log(msg)

2 Computed Enum
It  can include members with computed numeric value. The value of an enum member can be either a constant or computed.

Example:

enum PrintMedia {
    Newspaper = 1,
    Newsletter = getPrintMediaCode('newsletter'),
    Magazine = Newsletter * 3,
    Book = 10
}

function getPrintMediaCode(mediaName: string): number {
    if (mediaName === 'newsletter') {
        return 5;
    }
}

PrintMedia.Newsetter; // returns 5
PrintMedia.Magazine; // returns 15

When the enum includes computed and constant members, then uninitiated enum members either must come first or must come 
after other initialized members with numeric constants. The following will give an error.
enum PrintMedia {
    Newsletter = getPrintMediaCode('newsletter'),
    Newspaper, // Error: Enum member must have initializer
    Book,
    Magazine = Newsletter * 3,
}

The above enum can be declared as below.

enum PrintMedia {
    Newspaper,
    Book,
    Newsletter = getPrintMediaCode('newsletter'),
    Magazine = Newsletter * 3
}
// or
enum PrintMedia {
    Newsletter = getPrintMediaCode('newsletter'),
    Magazine = Newsletter * 3,
    Newspaper = 0,
    Book,
}

String Enum

It is same as numeric Enum, except that the enum values are initialized with string values.

The benefits of using string enums is that string enums offer better readability. If we were to debug a program, it is easier to read string values rather than numeric values.

enum Actors{
    PawanKalyan = "PAWANKALYAN",
    Chiranjeevi = "CHIRANJEEVI",
    MaheshBabu = "MAHESHBABU",
    RamCharan = "RAMCHARAN"
}
// Access String Enum
console.log(Actors.PawanKalyan);
console.log(Actors['RamCharan']);
Output:
PAWANKALYAN
RAMCHARAN

In the above example, we have defined a string enum, PrintMedia, with the same values as the numeric enum above, with the difference that these enum values are initialized with string literals. The difference between numeric and string enums is that numeric enum values are auto-incremented, while string enum values need to be individually initialized.

Heterogeneous Enum

Heterogeneous enums are enums that contain both string and numeric value

Example

enum Status {
    Active = 'ACTIVE',
    Deactivate = 1,
    Pending
}
// Access String Enum
console.log(Status.Active);
console.log(Status['Deactivate']);
console.log(Status['Pending']);

Output
ACTIVE 1 2

Reverse Mapping

Enum in TypeScript supports reverse mapping. It means we can access the value of a member and also a member name from its value. Consider the following example.

enum Actors{
    PawanKalyan = 1,
    Chiranjeevi,
    MaheshBabu,
    RamCharan
}

console.log(Actors.PawanKalyan);
console.log(Actors['RamCharan']);
console.log(Actors[3]);

Output
1 4 MaheshBabu

Let's see how TypeScript implements reverse mapping using the following example.

enum Actors{
    PawanKalyan = 1,
    Chiranjeevi,
    MaheshBabu,
    RamCharan
}

console.log(Actors);

The above example gives the following output in the browser console.
{
  '1': 'PawanKalyan',
  '2': 'Chiranjeevi',
  '3': 'MaheshBabu',
  '4': 'RamCharan',
  PawanKalyan: 1,
  Chiranjeevi: 2,
  MaheshBabu: 3,
  RamCharan: 4
}

Never

TypeScript introduced a new type which indicates the values that will never occur.

The never type is used when you are sure that something is never going to occur. 

Example

function throwError(errorMsg: string): never {
    throw new Error(errorMsg);
}

function keepProcessing(): never {
    while (true) {
 console.log('This will never End')
}
}



No comments:

Post a Comment

Thank you for visiting my blog

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...