Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 291
inferno Avatar asked Apr 16 '15 18:04

inferno


People also ask

How do I create an instance of a class in TypeScript?

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.

How do you define a static class in TypeScript?

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.

Does TypeScript have static methods?

TypeScript allows us to encapsulate our static methods with access modifiers, just like regular methods.


1 Answers

Hack :)

static getInstance() {
     return new this;
}
like image 115
vasa_c Avatar answered Oct 29 '22 17:10

vasa_c