...

Web Technologies - TypeScript

Back to Course

Lesson Description


Lession - #1447 TypeScript Enums


An enum is a special" class" that represents a group of constants( unchangeable variables>
.

Enums come in two flavors
  • string and
  • numeric.

    Lets start with numeric.

    Numeric Enums- Default

    By default, enums will initialize the first value to 0 and add 1 to each additional value

    illustration
    
    enum CardinalDirections{
    North,
    East,
    South,
    West
    
    let currentDirection = CardinalDirections.North;
    / logs 0
    console.log( currentDirection>
    ; / throws error as' North' isn't a valid enum currentDirection = ' North';// Error" North" isn't assignable to type' CardinalDirections'. Numeric Enums- Initialized


    You can set the value of the first numeric enum and have it auto increment from that

    illustration
    
    enum CardinalDirections{
    North = 1,
    East,
    South,
    West
    }
    / logs 1
    (CardinalDirections.North>
    ; / logs 4 console.log(CardinalDirections.West>
    ; Numeric Enums- Completely Initialized


    You can assign unique number values for each enum value. also the values won't incremented automatically

    Illustration
    
    enum StatusCodes{
    NotFound = 404,
    Success = 200,
    Accepted = 202,
    BadRequest = 400
    
    / logs 404
    console.log(StatusCodes.NotFound>
    ; / logs 200 (StatusCodes.Success>
    ;


    String Enums
    Enums can also contain strings. This is more common than numeric enums, because of their readability and intent.

    Illustration

    
    enum CardinalDirections{
    North = ' North',
    East = " East",
    South = " South",
    West = " West"
    ;
    / logs" North"
    console.log(CardinalDirections.North>
    ; / logs" West" (CardinalDirections.West>
    ;




    Online compiler