-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Symbols in as const
objects should be unique symbols
#54100
Comments
as const
objects should have unique symbolsas const
objects should be unique symbols
Possibly related: #53276 |
@fatcerberus I'm not convinced this issue is related. |
@nstepien Note I said "related", not "duplicate". That said, I think the limitation here is that unique symbols explicitly have type |
Given const obj = { x: Symbol() } as const , would it be possible for its type to be Although that wouldn't work in a case like fn({ [dynamicKey]: Symbol() } as const) as there is no specific name to refer back to. Maybe |
I wonder if TS could use the description when available, i.e. |
That's expressible as Trying to fix this with an explicit annotation fails: // ERROR: Type 'symbol' is not assignable to type 'unique symbol'.
const myEnum: {readonly a:unique symbol} = { a: Symbol() }; The best I achieve is with a cast: const myEnum = { a: Symbol() } as { readonly a: unique symbol } But this doesn't provide the type safety you seek because unique symbols decay too easily: const myEnum = { a: Symbol() } as { readonly a: unique symbol }
const anotherEnum = { a: Symbol() } as { readonly a: unique symbol }
let b = myEnum.a
b = anotherEnum.a // OOPS! NO ERROR! |
Wrote up some of the related issue in #56535 (namely that the type system disregards the |
1 to this feature request. Running into a similar issue where I would like the type generic to prefer a unique symbol. e.g.
Doesn't use unique symbol by default:
Can assign to a const first, which works but requires a technically unnecessary variable declaration
Appending
Possibly off topic, but I wouldn't expect any of this unique functionality to apply to However it appears that is not the case:
|
Bug Report
π Search Terms
symbol object "as const"
π Version & Regression Information
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
Symbols in
as const
-ed objects should beunique symbol
s, instead they're of typesymbol
.π Expected behavior
When I write
I want
obj.a
to be aunique 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
and that works great, but I end up with many
const ... = Symbol()
which pollute the scope and can be misused, when I'd rather doThe text was updated successfully, but these errors were encountered: