Seeking alternatives to creating class instances without using the new keyword in TypeScript, I came across this excellent solution that works seamlessly in JavaScript.
The code found in the repository mentioned https://github.com/digital-flowers/classy-decorator presents a straightforward class decorator:
var classy = function classy() {
return function (Class) {
var _Class = function _Class() {
for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) {
rest[_key] = arguments[_key];
}
return new(Function.prototype.bind.apply(Class, [null].concat(rest)))();
};
_Class.prototype = Class.prototype;
return _Class;
};
};
When trying to use it with TypeScript like this:
@classy()
class Someone{
constructor(private name: string){}
}
debugger
let some1 = new Someone("john");
let some2 = Someone("joe") // some2 is also an instance of Someone! but TypeScript raises an error stating it's not callable
I have yet to delve into the details of the function decorator to fully comprehend it, and it does result in TypeScript errors although it functions correctly.
Is there a method to bypass the TypeScript error when creating instances without using new (let some2 = Someone("joe")
)