Indexed symbol types #60944
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
🔍 Search Terms
"non-unique symbol types", "symbol type with key", "indexed symbol types"
✅ Viability Checklist
⭐ Suggestion
TypeScript should be able to express symbol types indexed with their key, reflecting the behavior of JavaScript's
Symbol.for("some key")
, by a new syntax likesymbol<"some key">
.This feature won't break existing code if it doesn't come with a change to the types of
Symbol.for
,Symbol.keyFor
, andSymbol.prototype.description
, but I'd rather like to see it happen, possibly behind a new tsconfig option like"indexedSymbolTypeInference": true
.📃 Motivating Example
💻 Use Cases
1. What do you want to use this for?
Making multiple versions of the same library compatible.
Sometimes a library generates objects with a private property at a unique symbol key and use it as some kind of marker to statically or dynamically determine if an object is really generated or already processed with the library, while allowing users to define arbitrary properties on it as much as possible.
But what if a user has to end up depending on multiple versions of the library somehow? To address this, the library should accept objects from other versions of the same library, so the library might want to start using non-unique symbols for the purpose. This does work at runtime but not at compile time due to the absence of indexed symbol types.
Using a string key instead of a non-unique symbol key invades the string key space of such an object at runtime, and could conflict with an index signature at compile time.
2. What shortcomings exist with current approaches?
There's no current approaches for this.
3. What workarounds are you using in the meantime?
None.
The text was updated successfully, but these errors were encountered: