Last active
September 15, 2025 07:56
-
-
Save wentout/882395ce9612b19cbcacfd4f6ba3b827 to your computer and use it in GitHub Desktop.
Nominal Typing for JS
This file contains hidden or 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
| // 1. having strict names for Constructors | |
| const MyConstructorSymbol = Symbol('My Constructor'); | |
| const MyConstructor = function () { | |
| Reflect.defineProperty(this, 'tesingTheName', { | |
| get () { | |
| return this.constructor.name; | |
| } | |
| }); | |
| }; | |
| Reflect.defineProperty(MyConstructor, 'name', { | |
| get() { | |
| return MyConstructorSymbol; | |
| } | |
| }); | |
| Object.freeze(MyConstructor.prototype.constructor); | |
| console.log(1, MyConstructor.name); // Symbol(My Constructor) | |
| delete MyConstructor.name; | |
| console.log(2, MyConstructor.name); // Symbol(My Constructor) | |
| // 2. making IoC store | |
| const ConstructorsIoC = new Map(); | |
| ConstructorsIoC.set(MyConstructorSymbol, MyConstructor); | |
| // 3. getting the constructor instance from IoC | |
| const myInstance = new (ConstructorsIoC.get(MyConstructorSymbol)); | |
| console.log(myInstance.tesingTheName); // Symbol(My Constructor) | |
| console.log(myInstance instanceof MyConstructor); // trye | |
| // so we have full functionality covered here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment