microsoft / microsoft/TypeScript

Symbols in `as const` objects should be unique symbols

Aperta
#54,100 8 commenti 13 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

In Discussion Suggestion
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
1g 19h
PR unite (30g)
117

Descrizione

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];

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia dalla riproduzione collegata in TypeScript Playground e analizza come il checker inferisce i tipi per le espressioni Symbol() all’interno dei literal di oggetto as const. Il lavoro è completato quando il tipo inline MyEnumB usa membri unique symbol distinti e rifiuta un nuovo Symbol() nei casi di test mostrati.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
typescript
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.