microsoft / microsoft/TypeScript
Type safety for enum property names
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 1g 19h
- PR unite (30g)
- 117
Descrizione
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.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia con l’esempio TypeScript 3.4.3 e traccia il modo in cui il checker tipizza l’accesso indicizzato in AnEnum[AnEnum.aProperty]. Il lavoro è completato quando l’espressione viene accettata se assegnata a keyof typeof AnEnum, include undefined quando appropriato e non modifica il JavaScript emesso.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- typescript
- Ambito
- compilers
- Tipo di issue
- Funzionalità
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 38/100