Tags:

Back To Articles

Enums in Typescript

July 19, 2024

Article Image

Table of Contents

What is ENUM?

Simple definition:

A data type that is used for define a set of values for a variable. Enums can be numeric and string.

An example:


enum Colour {
    Red = 'red',
    Blue = 'blue',
    Green = 'green'
  }
  
  let mycolour: Colour = Colour.Red;
  
  console.log(`Colourname: ${mycolour}`);

In this code, I made an enum Colour with 3 values. The enum values are assigned with string literal (‘red’, ‘blue’, and ‘green’) I declared a variable called mycolour and assigned it the value from Colour enum, selecting the colour Red as Colour.Red. I used console.log which will show the selected colour. The output of this code will be,

Alt text

With the help of code snippets, let’s explore further using enum in various other parts of a project.


Using it in a function.

enum Colour {
    Red = 'red',
    Blue = 'blue',
    Green = 'green'
  }
  
function display(myColour: string, message: Colour): void {
    console.log(`${myColour}: ${message}`);
}

display("ColourName", Colour.Blue)

In this code, After declaring the enum Colour with string literals, I have used a function called display it takes two parameters, myColour (string and message (of type Colour). Further, I used console.log to log the message. And called display function with Colour.Blue. The output will be,

Alt text

Using it in an object

enum Colour {
    Red = 'red',
    Blue = 'blue',
    Green = 'green'
  }

const Person = {
    name: 'John',
    favouriteColour: Colour.Green,
    city: 'NYC'
  };

  console.log(`Favourite Colour: ${Person.favouriteColour}`);

In this code, after declaring an enum Colour with it’s string literals. Next, I created an object called Person and assigned it various properties such as name, favourite colour, city. Now I can specify the favourite colour from the Colour enum and specify whichever colour I want and it will show me that. Then with console log, I can see the favourite colour. The output will be,

Alt text

Summary

These were small examples with code snippets to demonstrate the use cases of enum string literals in different ways. In this article we also saw enums being used in functions and objects. You can experiment and learn furthermore!

References

https://www.typescriptlang.org/docs/handbook/enum.html