TypeScript create new instance from class in static context

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 very helpful if someone has done something like this before and can help me. Maybe there is a JavaScript way?

Thanks in advance.

+3


source to share


2 answers


Hack :)



static getInstance() {
     return new this;
}

      

+6


source


You can also use the class name, which in your example Base ,

static getInstance() {
   return new Base()
}

      

Below is an example which uses Greeter class name inside static function named createInstance , you can check the following example in 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.

-2


source







All Articles