Skip to content

Type of heterogeneous enum value can't be inferred correctly when used in object literal #33439

@whzx5byb

Description

@whzx5byb

TypeScript Version: 3.5.3

Search Terms:
heterogeneous enum value type

Code

const enum Heterogeneous {
  Foo = 1,
  Bar = 'zzz',
}

var a1: string = Heterogeneous.Bar; // <= OK. no error.
var a2: {name: string} = {name: Heterogeneous.Bar}; // <= Type 'Heterogeneous' is not assignable to type 'string'.

var b1: Heterogeneous = Heterogeneous.Bar; // Type of 'b1' is 'Heterogeneous'.
var b2 = {name: b1}; // Type of 'b2' is still inferred as '{name: Heterogeneous.Bar;}'
var b3: {name: string} = {name: b1}; // OK. 'Heterogeneous.Bar' is assignable to 'string'.

Expected behavior:
no error.
Actual behavior:
var a2: {name: string} = {name: Constants.Bar}; // <= Type 'Constants' is not assignable to type 'string'.ts(2322)

I often use a heterogeneous const enum as a constant provider, for compile time optimizing.
Specifying the string type literal explicitly will work, like:

var a2: {name: string} = {name: <string>Heterogeneous.Bar};

but it looks verbose.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: enumEnums and their associated types/values

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions