Repository navigation
Description
Search Terms
Symbol, unique, generated, function call
Suggestion
With two functions returning unique symbol.
declare function randomSymbol(): { readonly id: unique symbol };
declare function randomSymbol2(): { readonly id: unique symbol };When comparing the symbol types when calling these two functions, we get a (correct) error from the compiler telling us that these types are incompatible.
const a = randomSymbol();
const b = randomSymbol2();
a.id === a.id;
a.id === b.id; // TS ERROR: Expected behaviour. 👍 If we call the same function two times though, the types are the same.
const a = randomSymbol();
const b = randomSymbol();
a.id === a.id;
a.id === b.id; // NO ERROR: But I would expect these two types to be different too 👎 I understand that this can be expected in some cases, though there is currently no way to tell the compiler to generate a different unique symbol for each function call.
Use Cases
My current use-case is for creating two objects using the same constructor, that are structurally identical, but that would not be compatible between them (kind of opaque types).
Maybe this should be through the usage of a new keyword to prevent compatibility issues with existing codebases.
Examples
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Activity
RyanCavanaugh commentedon Aug 20, 2020
There are two valid interpretations of what this means:
It's not really obvious how you would reason about the second one, since there's not any tracking of any sort of "This symbol came from this invocation" or a way to talk about that in a type syntax position.
typescript-bot commentedon Aug 22, 2020
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.
ExE-Boss commentedon Jan 25, 2021
Ryan Cavanaugh (@RyanCavanaugh)
To disambiguate those cases, it might be a good idea to use
new symbolfor the second case: #37469jcalz commentedon Feb 6, 2022
This already happens magically when you assign the value returned from
Symbolto a new variable, which gets inferred asunique symbol, right? So the ask here (and part of #37469) is to express whatSymbol()does in the type system.