microsoft / microsoft/TypeScript
Type of heterogeneous enum value can't be inferred correctly when used in object literal
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the reported TypeScript 3.5.3 behavior with the heterogeneous const enum and object-literal examples in the issue. Compare the inferred types and assignment errors for a direct enum member, an annotated variable, and an inferred object; done means the direct object literal assignment accepts the string-valued member without an explicit type assertion and existing inference behavior remains correct.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100