microsoft / microsoft/TypeScript

Allow iterating through enum variants with for of

Abierto
#42,457 7 comentarios 19 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Awaiting More Feedback Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

Suggestion

🔍 Search Terms

enum, iterate, variants

✅ Viability 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, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Note that "is this a runtime feature?" doesn't really apply in this case since enums are already a runtime feature (maybe the only one?). This suggestion just modifies the compilation output slightly.

⭐ Suggestion

The Typescript code for an enum...

enum Colour {
  Red,
  Green,
  Blue,
}

...generates Javascript like this:

var Colour;
(function (Colour) {
    Colour[Colour["Red"] = 0] = "Red";
    Colour[Colour["Green"] = 1] = "Green";
    Colour[Colour["Blue"] = 2] = "Blue";
})(Colour || (Colour = {}));

Unfortunately there's no nice way to iterate over the enum values. The prevailing suggestion on these two very highly upvoted StackOverflow questions is to use for in and then filter out the reverse mapping entries using typeof. That sucks:

  • It's very hacky. Probably really buggy.
  • The types are wrong - you get string or number instead of Colour.
  • It can't handle duplicated enum variants, e.g. enum { Zero = 0, None = 0, ...}, although I'm not 100% sure how duplicates should be handled anyway.

I propose that the above enum code should compile to something like this:

var Colour;
(function (Colour) {
    Colour[Colour["Red"] = 0] = "Red";
    Colour[Colour["Green"] = 1] = "Green";
    Colour[Colour["Blue"] = 2] = "Blue";
    Colour[Symbol.iterator] = function* () {
      yield 0;
      yield 1;
      yield 2;
    };
})(Colour || (Colour = {}));

This would allow you to write:

function paintColour(c: Colour) {...}

for (const c of Colour) {
  paintColour(c);
}

📃 Motivating Example / Use Cases

Probably the most common use is generating UI from enums (e.g. a colour drop-down), but this is very general purpose. The StackOverflow questions linked above demonstrate how much people want this. We've come across this twice already in our code - once for UI and once for collecting data per enum variant, e.g.:

enum Category {
  Code,
  Data,
  Constant,
  Variable,
  Temporary,
  ... lots more ...
}

const totals: Map<Category, number> = new Map();

// Add a 0 entry for all entries.
for (const cat of Category) {
  totals.set(cat, 0);
}

for (const variable of ...) {
  totals.set(totals.get(variable.category) + variable.size);
}

Note there is a related but slightly different bug here: #39627 but it's more about how for in does unexpected things than about making for of work. I don't think it really matters since you should never ever use for in anyway.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

El issue no especifica archivos de implementación ni pruebas. Empieza por localizar la emisión de enums y el manejo de for-of del compilador; después, revisa cómo debería comportarse la iteración generada para valores de enum numéricos, de tipo string y duplicados. Se considera terminado cuando haya un diseño acordado y las pruebas correspondientes del compilador que cubran la salida propuesta y la comprobación de tipos.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
typescript
Área
compilers
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.