Static constructor in TypeScript

Last week I was training an Angular 2 course in Denmark when I came to the realisation that static constructors are missing in TypeScript (and therefore also in EcmaScript 6)

So, I decided to find a workaround and found a way to do it.

It might not be the best code, but I wanted to share it with you anyway.

The solution is to create a decorator as you can see below:

    //Decorator declaration
    function construct(target: any) {
        target.construct();
    }

    @construct
    class MyClass {
        static Name: string;

        static construct() {
            this.Name = "Done";
        }
    }

    let test = MyClass.Name;
    console.log(test);

Ronald Harmsen

I'm a software developer. When I'm not developing software I'm training & coaching other developers, speaking on a conference or fiddling with some technical stuff.

Arnhem, The Netherlands

Subscribe to Ronald to the cloud

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!