microsoft / microsoft/TypeScript
Symbols in `as const` objects should be unique symbols
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
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];
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked TypeScript Playground reproduction and inspect how the checker infers types for Symbol() expressions inside as const object literals. Done means the inline MyEnumB type uses distinct unique symbol members and rejects a fresh Symbol() in the shown test cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 45/100