Suparnar Taina

Suparnar Taina

1582263000

What is Enum in Typescript?

Introduction

In this article you will learn about Enum in Typescript in detail. This article will help beginners to understand the concept.

What is Enum?

  • The short form of enumeration is enum.
  • It is used as a type with some set of values called a named constant.
  • Inernally it holds numeric type values or in some cases we can create heterogeneous enums.
  • The enum keyword is used to define the enums.
  • We can create a distinct case so it makes it easy to document.
  • It forces us to use all possible values.
  • Access the enums using index or use dot operator after the enum name & named constant.
  • Initial value starts from 0 if we do not set any value.
  • Auto incremental is the best approach to use because we do not need to worry about the values.

Syntax

enum enumName{  
constant1, constant2, constant3...  
}  

Example

Consider  traffic signal lights as an example.

This is image title

We can access the elements using index or by constant name:

enum signalLights{  
   red, yellow, green  
}  
let result: string = signalLights[signalLights.red];  
console.log(result);  
console.log(signalLights[1]);  
let output: signalLights = (<any>signalLights)["yellow"];  
console.log(output);  

Output

red
yellow
1

Types of enums

Numeric enum

  • It is commonly used in all languages.
  • Initial value starts from 0 if we do not set any value.
  • Takes only numeric values.
  • enum keyword is used to declare the numeric type enum.
  • We can assign any value as per our requirements.
  • If our function returns any numeric value then we can use this function to initialize the constant.

Consider that in the below rainbowColors is enum & we have not initialized any constants, so it will starts with 0 value and the rest of the constants have auto increamemtal values.

**Example **

enum rainbowColors {  
    Red,  
    Orange,  
    Yellow,  
    Green,  
    Blue,  
    Indigo,  
    Violet,  
}  
console.log("color & index value is as follows");  
for (let item in rainbowColors) {  
    if (isNaN(Number(item))) {  
        console.log(item + " : " + < rainbowColors > rainbowColors[item]);  
    }  
}   

Output

color & index value is as follows:

Red : 0
Orange : 1
Yellow : 2
Green : 3
Blue : 4
Indigo : 5
Violet : 6

Consider the below example, rainbowColors is enum & the second element is initialized with value 1000. So it will be auto incremental to the  remaining constants. It will print on the console.

**Example **

enum rainbowColors {  
    Red,  
    Orange = 1000,  
    Yellow,  
    Green,  
    Blue,  
    Indigo,  
    Violet,  
}  
console.log("color & index value is as follows");  
for (let item in rainbowColors) {  
    if (isNaN(Number(item))) {  
        console.log(item + " : " + < rainbowColors > rainbowColors[item]);  
    }  
}   

Output

color & index value is as follows,

Red : 0
Orange : 1000
Yellow : 1001
Green : 1002
Blue : 1003
Indigo : 1004
Violet : 1005

Using function in enum

Consider the below example. We can use function in enum if we are returning the value from the function. It is used when the user needs to do any calculation. Suppose we need to calculate the total minutes like 1 hour = 60 minute, 2 hour = 120 minute, then it will create one function which will do a calcuation & return values to enum constant:

Example

function Totalminute(hr: number): any{  
return 60 * hr;  
}  
enum hours  
{  
One = Totalminute(1) ,  
Two = Totalminute(2),  
Three = Totalminute(4),  
}  
console.log(hours.One);  
console.log(hours.Two);  
console.log(hours.Three);  

Output

60
120
240

String enum

It is same as the numeric enums,  we are just passing string values/literals to our enum constant. enum keyword is used to declare the enums.

Consider the below example, our vehicle is taking different kinds of turns, and we will define the enum as:

Example

enum vehicleTurn {  
    Left = "Left",  
        Right = "Right",  
        UTurn = "UTurn"  
}  
console.log(vehicleTurn.Left);  
console.log(vehicleTurn.Right);  
console.log(vehicleTurn.UTurn);  
}   

Output

Left
Right
UTurn

Heterogeneous enums

Typescript allows us to create a mixed type of enums.

This means we can assign numeric & string type values to enum.

Consider the below example, circleInfo has heterogeneous enum values.

Example

enum circleInfo {  
    Area = "area of circle",  
        Pie = 3.112,  
        Radius = 20  
}  
let result = circleInfo.Pie * circleInfo.Radius * circleInfo.Radius;  
console.log(circleInfo.Area + " is :" + result); 

Output

area of circle is :1244.8

Point A - Function & interface using enum

Consider the below example, clothSize is enum which contains some constants. IClothSize is an interface which contains two properties, key & value, having string & number type respectively.

Function is taking enum as a parameter & will print the data on the console.

Example

enum clothSize {  
    small,  
    medium,  
    large  
}  
interface IClothSize {  
    key: string,  
        value: number  
}  
  
function getClothSize(size: clothSize): IClothSize {  
    switch (size) {  
        case clothSize.small:  
            return {  
                key: clothSize[clothSize.small], value: 10  
            };  
        case clothSize.medium:  
            return {  
                key: clothSize[clothSize.medium], value: 20  
            };  
        case clothSize.large:  
            return {  
                key: clothSize[clothSize.large], value: 30  
            };  
    }  
}  
console.log("cloth is " + getClothSize(clothSize.small).key + " & value is " + getClothSize(clothSize.small).value);  
console.log("cloth is " + getClothSize(clothSize.medium).key + " & value is " + getClothSize(clothSize.medium).value);  

Output

cloth is small & value is 10

cloth is medium & value is 20

Point B - const enum

  • Typescript allows us to declare const enum.
  • const keyword is used.
  • It has a inlined values.
  • We can access enum using enum[‘ConstantName’]

Example

const enum myColor {  
    Red = 10,  
        White = Red * 4,  
        Blue = White + 10,  
        Yellow,  
}  
console.log(myColor.Red)  
console.log(myColor.White)  
console.log(myColor.Blue)  
console.log(myColor['Yellow'])   

Output

10
40
50
51

We will not be able to access enum using index in const enum like myColor[0], it will give us an error.

Point C

ES6 allows us to use map enum keys.

Example

enum classes {  
    I,  
    II,  
    III,  
    IV,  
    V  
}  
const ClassNames = new Map < number,  
    string > ([  
        [classes.I, '100'],  
        [classes.II, '200'],  
        [classes.III, '300'],  
    ]);  
console.log(ClassNames);   

Output

Map(3) {0 => “100”, 1 => “200”, 2 => “300”}

We will modify the above example, we can use this into a classes as below.

Note

User can modify the code as per their requirement.

Example

enum classes {  
    I,  
    II,  
    III,  
    IV,  
    V  
}  
const ClassNames = new Map < number,  
    string > ([  
        [classes.I, '100'],  
        [classes.II, '200'],  
        [classes.III, '300'],  
    ]);  
class AllStandards {  
    public allNames: object;  
    constructor() {  
        this.allNames = ClassNames;  
    }  
}  
let obj: AllStandards = new AllStandards();  
console.log(obj.allNames);   

Output

Map(3) {0 => “100”, 1 => “200”, 2 => “300”}

Point D - export enum

  • typescript allows us to export the enum.
  • export keyword is used before the enum.
  • import is used to import that enum file.

We can declare the enum like this:

export enum sportActivities {Football, Cricket,Badminton, Tennis}  

To import the enum in .ts,  i.e.; typescript file looks like this:

import {sportActivities} from '../enums'  

Summary

In this article, you learned about enum in Typescript. Thanks for reading!

#typescript #angular #Enum in Typescript

What is GEEK

Buddha Community

What is Enum in Typescript?
Suparnar Taina

Suparnar Taina

1582263000

What is Enum in Typescript?

Introduction

In this article you will learn about Enum in Typescript in detail. This article will help beginners to understand the concept.

What is Enum?

  • The short form of enumeration is enum.
  • It is used as a type with some set of values called a named constant.
  • Inernally it holds numeric type values or in some cases we can create heterogeneous enums.
  • The enum keyword is used to define the enums.
  • We can create a distinct case so it makes it easy to document.
  • It forces us to use all possible values.
  • Access the enums using index or use dot operator after the enum name & named constant.
  • Initial value starts from 0 if we do not set any value.
  • Auto incremental is the best approach to use because we do not need to worry about the values.

Syntax

enum enumName{  
constant1, constant2, constant3...  
}  

Example

Consider  traffic signal lights as an example.

This is image title

We can access the elements using index or by constant name:

enum signalLights{  
   red, yellow, green  
}  
let result: string = signalLights[signalLights.red];  
console.log(result);  
console.log(signalLights[1]);  
let output: signalLights = (<any>signalLights)["yellow"];  
console.log(output);  

Output

red
yellow
1

Types of enums

Numeric enum

  • It is commonly used in all languages.
  • Initial value starts from 0 if we do not set any value.
  • Takes only numeric values.
  • enum keyword is used to declare the numeric type enum.
  • We can assign any value as per our requirements.
  • If our function returns any numeric value then we can use this function to initialize the constant.

Consider that in the below rainbowColors is enum & we have not initialized any constants, so it will starts with 0 value and the rest of the constants have auto increamemtal values.

**Example **

enum rainbowColors {  
    Red,  
    Orange,  
    Yellow,  
    Green,  
    Blue,  
    Indigo,  
    Violet,  
}  
console.log("color & index value is as follows");  
for (let item in rainbowColors) {  
    if (isNaN(Number(item))) {  
        console.log(item + " : " + < rainbowColors > rainbowColors[item]);  
    }  
}   

Output

color & index value is as follows:

Red : 0
Orange : 1
Yellow : 2
Green : 3
Blue : 4
Indigo : 5
Violet : 6

Consider the below example, rainbowColors is enum & the second element is initialized with value 1000. So it will be auto incremental to the  remaining constants. It will print on the console.

**Example **

enum rainbowColors {  
    Red,  
    Orange = 1000,  
    Yellow,  
    Green,  
    Blue,  
    Indigo,  
    Violet,  
}  
console.log("color & index value is as follows");  
for (let item in rainbowColors) {  
    if (isNaN(Number(item))) {  
        console.log(item + " : " + < rainbowColors > rainbowColors[item]);  
    }  
}   

Output

color & index value is as follows,

Red : 0
Orange : 1000
Yellow : 1001
Green : 1002
Blue : 1003
Indigo : 1004
Violet : 1005

Using function in enum

Consider the below example. We can use function in enum if we are returning the value from the function. It is used when the user needs to do any calculation. Suppose we need to calculate the total minutes like 1 hour = 60 minute, 2 hour = 120 minute, then it will create one function which will do a calcuation & return values to enum constant:

Example

function Totalminute(hr: number): any{  
return 60 * hr;  
}  
enum hours  
{  
One = Totalminute(1) ,  
Two = Totalminute(2),  
Three = Totalminute(4),  
}  
console.log(hours.One);  
console.log(hours.Two);  
console.log(hours.Three);  

Output

60
120
240

String enum

It is same as the numeric enums,  we are just passing string values/literals to our enum constant. enum keyword is used to declare the enums.

Consider the below example, our vehicle is taking different kinds of turns, and we will define the enum as:

Example

enum vehicleTurn {  
    Left = "Left",  
        Right = "Right",  
        UTurn = "UTurn"  
}  
console.log(vehicleTurn.Left);  
console.log(vehicleTurn.Right);  
console.log(vehicleTurn.UTurn);  
}   

Output

Left
Right
UTurn

Heterogeneous enums

Typescript allows us to create a mixed type of enums.

This means we can assign numeric & string type values to enum.

Consider the below example, circleInfo has heterogeneous enum values.

Example

enum circleInfo {  
    Area = "area of circle",  
        Pie = 3.112,  
        Radius = 20  
}  
let result = circleInfo.Pie * circleInfo.Radius * circleInfo.Radius;  
console.log(circleInfo.Area + " is :" + result); 

Output

area of circle is :1244.8

Point A - Function & interface using enum

Consider the below example, clothSize is enum which contains some constants. IClothSize is an interface which contains two properties, key & value, having string & number type respectively.

Function is taking enum as a parameter & will print the data on the console.

Example

enum clothSize {  
    small,  
    medium,  
    large  
}  
interface IClothSize {  
    key: string,  
        value: number  
}  
  
function getClothSize(size: clothSize): IClothSize {  
    switch (size) {  
        case clothSize.small:  
            return {  
                key: clothSize[clothSize.small], value: 10  
            };  
        case clothSize.medium:  
            return {  
                key: clothSize[clothSize.medium], value: 20  
            };  
        case clothSize.large:  
            return {  
                key: clothSize[clothSize.large], value: 30  
            };  
    }  
}  
console.log("cloth is " + getClothSize(clothSize.small).key + " & value is " + getClothSize(clothSize.small).value);  
console.log("cloth is " + getClothSize(clothSize.medium).key + " & value is " + getClothSize(clothSize.medium).value);  

Output

cloth is small & value is 10

cloth is medium & value is 20

Point B - const enum

  • Typescript allows us to declare const enum.
  • const keyword is used.
  • It has a inlined values.
  • We can access enum using enum[‘ConstantName’]

Example

const enum myColor {  
    Red = 10,  
        White = Red * 4,  
        Blue = White + 10,  
        Yellow,  
}  
console.log(myColor.Red)  
console.log(myColor.White)  
console.log(myColor.Blue)  
console.log(myColor['Yellow'])   

Output

10
40
50
51

We will not be able to access enum using index in const enum like myColor[0], it will give us an error.

Point C

ES6 allows us to use map enum keys.

Example

enum classes {  
    I,  
    II,  
    III,  
    IV,  
    V  
}  
const ClassNames = new Map < number,  
    string > ([  
        [classes.I, '100'],  
        [classes.II, '200'],  
        [classes.III, '300'],  
    ]);  
console.log(ClassNames);   

Output

Map(3) {0 => “100”, 1 => “200”, 2 => “300”}

We will modify the above example, we can use this into a classes as below.

Note

User can modify the code as per their requirement.

Example

enum classes {  
    I,  
    II,  
    III,  
    IV,  
    V  
}  
const ClassNames = new Map < number,  
    string > ([  
        [classes.I, '100'],  
        [classes.II, '200'],  
        [classes.III, '300'],  
    ]);  
class AllStandards {  
    public allNames: object;  
    constructor() {  
        this.allNames = ClassNames;  
    }  
}  
let obj: AllStandards = new AllStandards();  
console.log(obj.allNames);   

Output

Map(3) {0 => “100”, 1 => “200”, 2 => “300”}

Point D - export enum

  • typescript allows us to export the enum.
  • export keyword is used before the enum.
  • import is used to import that enum file.

We can declare the enum like this:

export enum sportActivities {Football, Cricket,Badminton, Tennis}  

To import the enum in .ts,  i.e.; typescript file looks like this:

import {sportActivities} from '../enums'  

Summary

In this article, you learned about enum in Typescript. Thanks for reading!

#typescript #angular #Enum in Typescript

TypeScript Enums or Objects?

TypeScript’s have Enums, which is a great language feature. However when you’re writing libraries and exposing functions that try and require Enums it can make for a bad user experience.

Instead you should use regular ol’ JavaScript objects - but super charged with TypeScript!

#typescript #enums

Noah  Sykes

Noah Sykes

1597206616

Using Enums in TypeScript

How to create enums in TypeScript with their benefits and drawbacks.

In this post, we will cover what TypeScript enums are and how to create them. We’ll also discover the drawbacks of enums and use cases where they work well.

What is an enum?

An enum is short for enumeration and is a type that represents named constants. If the meaning of the constant’s value is not apparent, it can make code easier to understand.

Consider the examples below:

if (status === 5) {
  // do something
}

if (status === JobStatus.Completed) {
  // do something
}

The second if statement uses an enum. It is arguably easier to understand than the first if statement.

#typescript #enums #developer

Cayla  Erdman

Cayla Erdman

1601549700

What’s New In Typescript 4.0?

Today I am going to talk about new features in Typescript 4.0.

TypeScript 4.0 comes with lots of new features to make JavaScript development easier.

Labeled Tuple Elements

You can label tuple elements.

You can write:

type Range = [start: number, end: number];

to restrict args to have a string and a number.

you can also write:

type Foo = [first: number, second?: string, ...rest: any[]];

to have rest entries in your tuple.

If your tuple has type Foo, then the tuple starts with a number and a string.

Then the rest of the entries can be anything.

Labels don’t require you to name your variables differently when destructuring.

For example, if you have:

function foo(x: [first: string, second: number]) {
  const [a, b] = x;
}

then you can name the destructured variables anything you want.

#software-development #typescript-with-react #typescript #typescript-4 #react native

Christa  Stehr

Christa Stehr

1599308024

Microsoft Releases TypeScript 4.0 With Speed Boosting Features

icrosoft recently announced the availability of TypeScript version 4.0. The developers at the tech giant claimed that this version of the language represents the next generation of TypeScript with more expressivity, productivity as well as scalability.

Developed by the tech giant, TypeScript is an open-source programming language that is built on top of JavaScript by adding syntax for static type definitions. The types in this language provide a way to describe the shape of an object, providing better documentation as well as allowing TypeScript to validate that the code is working correctly.

According to the latest Stack Overflow Developers survey 2020, it secured the second position as the most loved language and  9th position among 25 programming languages as the most commonly used programming language by the developers. In one of our articles, we discussed how TypeScript weighs over other programming languages.

It is one of the fastest-growing programming languages among the developers. The motive behind this language is that while writing down the types of values and where they are used, developers can use TypeScript to type-check the code and let them know about mistakes before they run the code. TypeScript compiler can be used to strip away types from the code, leaving them with clean, readable JavaScript that runs anywhere.

In the present scenario, TypeScript is a core part of many developer’s JavaScript stack. The language adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host and on any operating systems.

The program manager of TypeScript, Daniel Rosenwasser, said in a blog post, “In our past two major versions, we looked back at some highlights that shined over the years. For TypeScript 4.0, we’re going to keep up that tradition.”

What’s New?

Based on the feedback by the developer’s community, TypeScript 4.0 includes many intuitive features that are focussed on boosting the performance of this language. Some of them are mentioned below-

Speed Improvements in build mode with –noEmitOnError

According to Rosenwasser, previously, compiling a program after a previous compile with errors under incremental would result in extremely slow performance when using the –noEmitOnError flag. The reason is, none of the information from the last compilation would be cached in a .tsbuildinfo file based on the –noEmitOnError flag.

But now TypeScript 4.0 changes this. The new update provides a great speed boost in these scenarios, and in turn, improves the build mode scenarios, which imply both –incremental and –noEmitOnError.

#developers corner #microsoft #microsoft releases typescript 4.0 #programming language #programming language with high salary #typescript #typescript 4.0