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.