Skip to content

Instantly share code, notes, and snippets.

@wentout
Last active September 15, 2025 07:56
Show Gist options
  • Save wentout/882395ce9612b19cbcacfd4f6ba3b827 to your computer and use it in GitHub Desktop.
Save wentout/882395ce9612b19cbcacfd4f6ba3b827 to your computer and use it in GitHub Desktop.
Nominal Typing for JS
// 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