microsoft / microsoft/TypeScript
Symbols in `as const` objects should be unique symbols
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.4k
- Merge medio
- 1 d 19 h
- PR fusionados (30 d)
- 117
Descripción
Bug Report
🔎 Search Terms
symbol object "as const"
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about symbol
⏯ Playground Link
Playground link with relevant code
💻 Code
const A = Symbol();
const B = Symbol();
const MyEnumA = { A, B } as const;
// ^?
type MyEnumA = typeof MyEnumA[keyof typeof MyEnumA];
// ^?
// good
function testA(val: MyEnumA) {}
testA(MyEnumA.A);
testA(MyEnumA.B);
testA(Symbol()); // good type error
const MyEnumB = { C: Symbol(), D: Symbol() } as const;
// ^?
// should not use generic "symbol" type
type MyEnumB = typeof MyEnumB[keyof typeof MyEnumB];
// ^?
// should not be symbol
function testB(val: MyEnumB) {}
testB(MyEnumB.C);
testB(MyEnumB.D);
testB(Symbol()); // should be a type error
🙁 Actual behavior
Symbols in as const-ed objects should be unique symbols, instead they're of type symbol.
🙂 Expected behavior
When I write
const obj = { a: Symbol() } as const;
I want obj.a to be a unique symbol.
What I'm trying to do is replace TS enums with symbol-based object "enums" in some scenarios, as it gives me greater typecheck-time and runtime guarantees.
I can do
const A = Symbol();
const MyEnum = { A } as const;
type MyEnum = typeof MyEnum[keyof typeof MyEnum];
and that works great, but I end up with many const ... = Symbol() which pollute the scope and can be misused, when I'd rather do
const MyEnum = { A: Symbol() } as const;
type MyEnum = typeof MyEnum[keyof typeof MyEnum];
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza con la reproducción vinculada de TypeScript Playground e inspecciona cómo el checker infiere tipos para expresiones Symbol() dentro de literales de objeto as const. Se considera terminado cuando el tipo inline MyEnumB usa miembros unique symbol distintos y rechaza un Symbol() nuevo en los casos de prueba mostrados.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- typescript
- Área
- compilers
- Tipo de issue
- Error
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bien especificado
- Aptitud para principiantes
- 45/100