inferno
inferno

Reputation: 233

TypeScript create new instance from class in a 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 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

Answers (2)

Anmol Saraf
Anmol Saraf

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

vasa_c
vasa_c

Reputation: 1004

Hack :)

static getInstance() {
     return new this;
}

Upvotes: 17

Related Questions