Skip to content

Initializing enum members with another string enum causes incorrect/inconsistent types #26522

@devrelm

Description

@devrelm

TypeScript Version: 2.4.1 through 3.1.0-dev.20180817

Search Terms:

  • string enum values act like numbers
  • inconsistent string enum types
  • string enum of string enum

Code

enum Foo {
    Foo1 = 'hello',
    Foo2 = 'goodbye',
}

enum Bar {
    Bar1 = Foo.Foo1,
    Bar2 = Foo.Foo2,
}

const myStringFunc = (baz: string) => console.log(baz);

const myFooFunc = (baz: Foo) => myStringFunc(baz);

const myBarFunc = (baz: Bar) => myStringFunc(baz);
                                          // ~~~ Argument of type 'Bar' is not
                                          // assignable to parameter of type 'string'.

// This compiles fine! TypeScript thinks baz is a number!
const myOddFunc = (baz: Bar) => baz.toExponential();

Expected behavior:
String enums like Bar that are initialized with other string enum values should be properly typed as a string enum.

Actual behavior:
Bar is inconsistently typed as a numeric enum, as evidenced by baz.toExponential() not causing a compiler error.

To make it more fun, the members of Bar even autocomplete and hint as the correct string literals:
image
image

But the members of Bar themselves autocomplete members of Number.prototype:
image

Playground Link:
here

Related Issues:
None that I could find

Metadata

Metadata

Assignees

No one assigned

    Labels

    Breaking ChangeWould introduce errors in existing codeIn DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions