Tuesday, June 7, 2016

TypeScript - Static Constructor

TypeScript doesn't have inbuilt support for static constructor. But when we code applications there will be many scenarios where we need to execute something once for a class. Below is one example we can workaround this in TypeScript
module Company.Application.Feature.SubFeature {
    "use strict";
    export class MyClass {
        private static _constructor:void = (() => {
            var obj: MyClass = new MyClass();
            obj.setup();
        })();
        constructor() {
        }
        setup() {
        }
    }
}

How it works

The _constructor line will be executed as IIFE. ie the parameter less arrow function is executed when the script is loaded and assign void/undefined to _constructor variable.

Difference with .Net static constructor

In .Net the static constructor is kind of lazy.ie it will execute when that class is first referred for object creation or any other static method is called. But this workaround in TypeScript executes the static constructor soon after the script is loaded.


No comments: