Reputation: 233
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.
Upvotes: 7
Views: 7758
Reputation: 15743
You can also use class name itself which in your example is Base,
static getInstance() {
return new Base()
}
Another example is below which uses Greeter class name inside static function called createInstance, you can test following example at TypeScript Playground
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
static createInstance(message: any) {
return new Greeter(message);
}
}
let greeter = Greeter.createInstance("world");
let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
alert(greeter.greet());
}
document.body.appendChild(button);
Hope it helps.
Upvotes: -4