3.5 Local types

Local types allow us to declare a type inside the declaration of another type.

Getting Ready

All you need to be able to use local types is an installation of TypeScript version 2.0 or higher.

How to do it…

TypeScript 1.6 onwards allow us to use the keywords related with the declaration of types (class, interface, type…) inside the declaration of a type:

class A {
	x: number;
	do() {
	  class B {
	    y: string;
	  }
	  return new B();
	}
}

How it works…

The TypeScript classes are just translated into JavaScript classes keeping the original position within the parent type. For example, the B class is declared inside the do method, which belongs to the A class.

var A = (function () {
    function A() {
    }
    A.prototype.do = function () {
        var B = (function () {
            function B() {
            }
            return B;
        })();
        return new B();
    };
    return A;
})();

Source Code

Local types


Shiv Kushwaha

Author/Programmer