Type of reverse mappings of numeric enums is a `string` instead of `keyof typeof Enum`
See original GitHub issueTypeScript Version: 4.0.0-dev.20200526
Search Terms: enum numeric enum reverse enum
Code
enum Enum {
one = 1,
two = 2,
}
const a: keyof typeof Enum = Enum[Enum.one]; // (1)
const b = Enum[0]; // (2)
console.log(a, b);
Expected behavior:
When a numeric enum is indexed by itself the value should be of type keyof typeof Enum
:
No error on line (1).
Error Property '0' does not exist on type 'typeof Enum'
on line (2).
Actual behavior:
When a numeric enum is indexed by a number (including itself) the value is of type string
:
Error Type 'string' is not assignable to type '"one" | "two"'
on line (1).
No error on line (2).
Playground Link: Provided
Related Issues:
Issue Analytics
- State:
- Created 3 years ago
- Reactions:12
- Comments:6
Top Results From Across the Web
Handbook - Enums - TypeScript
TypeScript provides both numeric and string-based enums. ... Instead, use keyof typeof to get a Type that represents all Enum keys as strings....
Read more >Getting the enum key with the value string (reverse mapping ...
Workaround: Getting a reverse mapping for string enum members. To get the key of an enum member by its value, you have to...
Read more >TypeScript string enums, and when and how to use them
In this section, we are going to explore string enums in TypeScript. ... Instead, using keyof typeof will get you a type that...
Read more >12 TypeScript enums: How do they work? What can they be ...
With enums, TypeScript lets us define similar types ourselves. ... Instead of numbers, we can also use strings as enum member values: enum...
Read more >Wonderland of TypeScript enums - Alex Klaus
Enums are real objects that exist at runtime. However, instead of the keyof keyword you need to use keyof typeof to get all...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I can certainly agree that enum reverse mappings should have type
keyof typeof Enum
rather thanstring
. This loses information and can necessitate an unnecessary cast.I would like to see this feature as well