-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Allow enum variant names that collide with existing types (#70)
According to [The Big O of Code Reviews](https://www.egorand.dev/the-big-o-of-code-reviews/), this is a O(_n_) change. This small PR tweaks the Variant classes for our typescript version of Tagged Enums, to allow Variants to have names of existing types. For example, it's not uncommon for Rust programs to have enums constructed like so: ```rs struct Dog {} struct Cat {} enum Animal { Dog(Dog), Cat(Cat), } ``` The way we've modeled tagged enums are with a frozen object containing a class for each Variant. So this would translate to: ```typescript type Dog = …; // Dog defined elsewhere type Cat = …; const Animal = (() => { class Dog { constructor(public value: Dog) { // This Dog value is the wrong type! // value is the type of the Variant class. } } class Cat { constructor(public value: Cat) {} } return Object.freeze({ Dog, Cat }); })(); ``` This commit changes the naming of the Variant class: ```typescript type Dog = …; // Dog defined elsewhere type Cat = …; const Animal = (() => { class Dog_ { constructor(public value: Dog) { // There is no variant class called Dog yet, just Dog_, // so value is the correct type. } } class Cat_ { constructor(public value: Cat) {} } // We rename the Dog_ variant class as Dog here, // so the only way to access this class is via Animal.Dog. return Object.freeze({ Dog: Dog_, Cat: Cat_ }); })(); ```
- Loading branch information
Showing
3 changed files
with
111 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters