Home > Net >  typescript buggy behavior with enum
typescript buggy behavior with enum

Time:08-30

Lets take a look at this example. First i create enum

enum myEnum {
  a = 'a', 
  b = 'b'
}

now i make similar enum but I add one more numeric ! ( this is important) value

enum myExtendedEnum {
    a = "a", 
    b = "b", 
    //this can be any number 
    c = 11, 
}

now look at this.

const returnsMyEnum = function() : myEnum {
    return 48;  
}

const returnMyExtendedEnum = function() : extendedEnum {
    return 48; 
}

Guess which one of above function are buggy for typescript? I would expect both but nope, only the returnsMyEnum one. Do you understand whats happen here or i should rather open bug report in typescript repository?

CodePudding user response:

This is an interesting question. What you are using here is called heterogeneous enums.

But the problem doesn't come from that. It comes from the fact that you are using numeric values.

This example will compile just fine:

enum NumericEnum {
  a = 23
}

const numeric = (): NumericEnum => 4;

Any enum that has a numeric value will widen the type to numeric. The reason for this is bitwise operators. People are used to use numeric enums assign power of 2 values and bitwise to signal multiple values. Something like this:

enum Flags {
 value1 = 1
 value2 = 2
 value3 = 4
 value4 = 8
}

Now you can use something like this Flags.value1 | Flags.value4. This value signals that you have both value1 and value4. Because this is a common use TS decided to widen the type to number.

  • Related