In ES6 classes, I find myself creating static create methods, prefering to do ClassName.create() rather than new ClassName() or new ClassName, since I have run into some silly errors having to do with accessing properties on the newly created object; slipping up and doing new ClassName.methodCall() instead of (new ClassName).methodCall(). IMO it's cleaner to do ClassName.create().methodCall() and less prone to silly and difficult-to-catch errors.
However, it gets tedious and verbose to do this on every class, so I was wondering if there was a way to use TS/ES6 decorators so that I could do
@Creatable // or @Creatable()
class ClassName {
constructor(arguments: IArguments) {}
}
which would create a static create(arguments: IArguments) { return new this(arguments); } method on the class, with the same arguments, including types.
Is this possible, and if so how?
new ClassName(…).methodCall()works just fine. It's only when you omit the constructor argument list (new ClassName.methodCall()) that you need to group it into(new ClassName).methodCall()..create()pattern