TypeScript Modules


Modules allow you to organize your code. This makes your code easier to understand, maintain and debug. You can also share code.

In this example from the Udemy website in the course called Introduction to TypeScript, we will create two files: timesTwo.ts and util.ts. Our program will multiply a number by two and return the result.

timesTwo.ts

module Utility {

    export class Useful {
      timesTwo(n : number){
          return n * 2;
      }
    }
}

util.ts

/// <reference path="timesTwo.ts" />
var use = new Utility.Useful(); // create the object
console.log(use.timesTwo(9));

Modules export classes. The file timesTwo.ts exports a module that has a class.

To combine files in TypeScript we have to use the out flag.

Let’s extend our example here to have our module contain several very handy functions. We have changed the name from timesTwo.ts to times.ts.

times.ts

module Utility {

    export class Useful {
      timesTwo(n : number){ return n * 2; }
      timesThree(n : number){ return n * 3; }
      timesFour(n : number){ return n * 4; }
    }
}

util.ts

/// <reference path="times.ts" />
var use = new Utility.Useful(); // create the object
console.log(use.timesTwo(9));
console.log(use.timesThree(9));

Series Navigation<< TypeScript InheritanceTypeScript Modules Part 2 >>

Leave a comment

Your email address will not be published. Required fields are marked *