Using an enum inside string valued members

Viewed 830

Assuming these are my enums:

enum Direction {
    Up = `1`,
    Down = '2',
    Left = '3',
    Right = '4',
}

enum Direction2 {
    Up = Direction.Up
}

The above case is valid as long as the value of 2nd enum is from another Enum. But why this is not valid?

enum Direction2 {
    Up = Direction.Up,
    Down = '2'
}

I have looked into the typescript enum doc but cannot find any reason for it. From what I'm seeing, both values in Direction2 is a string, and there should be allowed. I'm aware this can be worked around if I change Direction2 to a json:

let Direction2 = {
    Up: Direction.Up,
    Down: '2'
}

but I would prefer to keep it as an enum.

1 Answers

Your syntax should be throwing the error:

Computed values are not permitted in an enum with string valued members.

From the Typescript lead developer, this is disallowed on purpose.:

String enums are syntactically differentiated from numeric enums by having string literals in all initialization positions. It's also the case that we need to produce a union type (instead of a branded primitive type) for a string literal enum, which aren't really sourced from consts without explicit type annotations.

https://github.com/Microsoft/TypeScript/issues/20440

So the issue you are having isn't the referencing of Enum declarations within other enums. It is just that they other enum values are string values. See the following:

// valid
enum Test{
    A = 1,
    B = 2
}
enum AnotherTest{
    A = Test.B,
    B = 2
}
/////////////////////////////
// valid
enum Test{
    A = "1",
    B = "2"
}
enum AnotherTest{
    A = Test.B,
    B = 2
}
/////////////////////////////
// INVALID
enum Test{
    A = "1",
    B = "2"
}
enum AnotherTest{
    A = Test.B,
    B = "2"
}
Related