1

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Well ineed this is heterogeneous enum. But it doesnt explain the source of fact one function is ok while another is not. Maybe i dont understand what you mean by widen the type to numeric. tsplay.dev/N9PO8w here we can see js output and i dont see anything special in the enum where one of the value is numeric.
It doesn't matter what code it gets generated. When using a numeric value, the type for the enum values is actually number and not your subset. That's why it's enough to have an enum with only one numeric value for the behaviour to be observable.
You might want to link to the handbook section on enum compatibility (although it just says enums are mutually compatible with number, which isn't true for string-only enums). You could also point to various GitHub issues like github.com/microsoft/TypeScript/issues/32690 to indicate that this is a known pain point for people
@jcalz Thank you for the links. I'll try yo be more diligent in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.