microsoft / microsoft/TypeScript
Type safety for enum property names
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Suggestion
Enums work in two directions, where an enum property value can be retrieved via AnEnum.aProperty and a property name can be retrieved via AnEnum[aValue]. In TypeScript 3.4.3, the type of the second expression is string. Instead, it should be equivalent to keyof typeof AnEnum | undefined.
Use Cases
While the nameof operator (suggested in #1579) does not exist yet, a construct such as AnEnum[AnEnum.aProperty] can currently be used to safely refer to an enum property name. Unfortunately, since the type of that expression is string it requires a cast when assigning it to a type safe target.
Examples
enum AnEnum { aProperty = 1, anotherProperty = 23, yetAnotherOne = 42 };
let target: keyof typeof AnEnum;
…
// Compilation error here: Type 'string' is not assignable to type '"aProperty" | "anotherProperty" | "yetAnotherOne"'.
target = AnEnum[AnEnum.aProperty];
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
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 with the TypeScript 3.4.3 example and trace how the checker types the indexed access in AnEnum[AnEnum.aProperty]. Done means the expression is accepted when assigned to keyof typeof AnEnum, includes undefined as appropriate, and does not change emitted JavaScript.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100