Why does Typescript doesn't check values number-enums?

Viewed 39

I noticed that if I have an enum that is composed of numbers, then basically TypeScripts allows assigning any number to the variable of such type:

enum EnumTestA {
    foo = 1,
    baz = 2
}

const testEnum1: EnumTestA = 4;

The above compile just fine. Why?

If I try to do the same with strings:

enum EnumTestB {
    foo = "FOO",
    baz = "BAZ"
}

const testEnum2: EnumTestB = "zzz";

Then it refuses to compile it as expected.

1 Answers

A common usage of enums is for bit-flags, which are essentially numbers with only one bit set, so their bitwise or (a single number) can be decomposed into the individual flags. If numerical values were checked, then something like the following wouldn't work:

enum Flags {
    FLAG1 = 1,
    FLAG2 = 2,
    FLAG3 = 4
};

const flags: Flags = Flags.FLAG1 | Flags.FLAG2;

And it would need a cast, which was deemed too annoying to have to deal with, so they decided to not check numerical values.

Related