1

I have enum as follows.

const enum Mode{
    Add=1,
    Edit=22
}
let currentMode:Mode=222222;

My Point is why it is considered a valid code. It should throw compile error on a compilation but it is not.

When we use an enum with Java or C# it enforces us to provide proper value.

Please share thoughts.

Sukesh Marla
  • 178
  • 11

2 Answers2

0

According to TypeScript documentation:

Enums allow us to define a set of named constants

i.e. enum is not a limited set of options, it's just a list of constants.

The code from your question:

const enum Mode{
    Add=1,
    Edit=22
}
let currentMode:Mode=222222;

let add: Mode = Mode.Add

will be compiled to the following JavaScript:

"use strict";
let currentMode = 222222;
let add = 1 /* Add */;

As you can see there won't be any object created for your const enum in JS. TypeScript compiler will place used enum's values at the places of usages instead.

As for the enum type in C#. You can do the same thing. Code listed below is valid C# code:

public enum Mode
{
    Add = 1,
    Edit = 2
}
...
Mode mode = (Mode)123;
Vitalii Ilchenko
  • 578
  • 1
  • 3
  • 7
0

use string enums or union types instead

The behavior of numeric enums that you describe is as intended as Typescript's bossman himself declares. See Issue 26362 for details.

If you want value safety (only valid underlying values are allowed) or true type safety, you'll have to use other options such as:

  • Union types (value-safe)

    type Mode = 'Add' | 'Edit'
    
  • String enums (type-safe)

    enum Mode {Add = 'add', Edit = 'edit'}
    

For an explanation of the above two options, and for more options, see this answer.

Inigo
  • 12,186
  • 5
  • 41
  • 70