Is there a way in TypeScript to create new instances from a static method in a generic way?
I want to do something like:
class Base {
static getInstance() {
return new self(); // i need this line :)
}
}
class Test extends Base {
}
class NextTest extends Base {
}
var test = Test.getInstance();
assert(test instanceof Test).toBe(true);
var nextTest = NextTest.getInstance();
assert(nextTest instanceof NextTest).toBe(true);
It would be really helpful if someone did something like this before and could help me. Maybe there is a JavaScript way?
Thanks in advance.
You can do this by using the new keyword, followed by a syntax similar to that of an arrow function, where the parameter list contains the parameters expected by the constructor and the return type is the class instance this constructor returns. The TypeScript compiler now will correctly compile your code.
A static class can be defined as a sealed class that cannot be inherited besides being inherited from an Object. static class cannot be instantiated, which means you cannot create the instance variable from the Static Class reference.
TypeScript allows us to encapsulate our static methods with access modifiers, just like regular methods.
Hack :)
static getInstance() {
return new this;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With