Modules helps in writing clean code like seperating modules for dataacces, UI and security. Each modules has a separate role of its own
like httpModule, routing module. Writing Modules in TS would create IIFE(Immediately Invoked Function Expression) in javascript file

module dataService{

}

So what is difference between class and module. Both are same except one. Classes are created in Global namespace.
However module can be either global or local.

class dataService{

}

Now lets wrap class with in module which is nothing more than namespace

module Shapes{
  export class Rectangle{

  } 

  export class Square{

  } 

  export class Triangle{

  } 
}

var objShapes:any = new Shapes.Square;

Simple Program for Logging Message using Module and Interface

interface ILoggerUtils {
    print(): void;
}

var LogLevel = {
    info: 1,
    Warn: 2,
    Error:3
}

module LogUtils {
    export class LoggerAtError implements ILoggerUtils {
        
    print(): void {
        console.log("Log Message during Error");
    }
}

export class LoggerAtInfo implements ILoggerUtils {
    print(): void {
        console.log("Log Message during Info");
    }
}

export class LoggerAtWarn implements ILoggerUtils {
    print(): void {
        console.log("Log Message during Warn");
    }
  }
}

window.onload = function () {
    var objLoggerUtil: ILoggerUtils;

    var logLevel = LogLevel.info;

    switch (logLevel) {
        case LogLevel.info:
            objLoggerUtil = new LogUtils.LoggerAtInfo();
            break;
        case LogLevel.Warn:
            objLoggerUtil = new LogUtils.LoggerAtWarn();
            break;
        case LogLevel.Error:
            objLoggerUtil = new LogUtils.LoggerAtError();
            break;
    }

    objLoggerUtil.print();
}

Output

Log Message during Info

Comments are closed.