microsoft / microsoft/TypeScript
Symbols in `as const` objects should be unique symbols
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.3k
- Ø Merge
- 1 T. 19 Std.
- Gemergte PRs (30 T.)
- 117
Beschreibung
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];
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit der verknüpften TypeScript Playground-Reproduktion und untersuche, wie der Checker Typen für Symbol()-Ausdrücke innerhalb von as const-Objektliteralen ableitet. Als abgeschlossen gilt die Aufgabe, wenn der Inline-Typ MyEnumB unterschiedliche unique symbol-Member verwendet und ein neues Symbol() in den gezeigten Testfällen ablehnt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Klar beschrieben
- Anfängerfreundlichkeit
- 45/100