Symbols produced by an alias of the Symbol constructor cannot be used as object keys in types/interfaces/classes, etc. #53282
Labels
Awaiting More Feedback
This means we'd like to hear from more people who would be helped by this feature
Suggestion
An idea for TypeScript
Bug Report
Symbols returned by an alias of the global Symbol constructor cannot be used as objects keys. See this playground example.
In and of itself this is not a bug per se, but it can result in increase bundle size when using a minifier such as terser. Terser does not mangle global names such as Math, Symbol, etc. (see: terser/terser#1337), so a common trick to avoid them reappearing in minified code is to assign the global name to a local variable.
For instance, consider the following typescript code that uses the globals Symbol and Math: playground link
when compiled to javascript by TS it generates the following output:
and when minified using terser you get the following output (you can try this using https://try.terser.org):
Now consider this minor tweak to the original code, which aliases the global Math name to a local variable: playground link
when compiled to javascript by TS it generates the following output:
which terser can minify to:
Obviously in this small example there isn't a significant difference in minified size, but in a large library that includes hundreds of calls to a top level name, this reduction can be significant. Its not uncommon to re-export math functions from an internal module to enable this type of minified output when one is focused on reducing output size.
Unfortunately, for libraries written in TS that choose to use symbols for object keys, class methods, etc. the resulting output can become littered with invocations of the Symbol constructor and there is no typesafe way in typescript to work around this.
🔎 Search Terms
Symbol
🕗 Version & Regression Information
4.95
⏯ Playground Link
Symbols returned from alias to Symbol not working as keys: playground example
💻 Code
🙁 Actual behavior
Symbols returned by aliases of the global Symbol constructor are not unique and cannot be used as keys in interfaces and types.
🙂 Expected behavior
Symbols returned by aliases of the global Symbol constructor should be unique symbols usable as keys in interfaces and types.
The text was updated successfully, but these errors were encountered: