About Me

Followers

My Visual Studio Achievements

Twitter

Tuesday, June 7, 2016

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

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.