TypeScript ambient module tutorial

TypeScript ambient module:

As we discussed in earlier tutorials TypeScript provides the facility to safely and easily use existing JavaScript libraries like jquery, angularjs, nodejs etc. Ambient declarations allow us to safely use existing popular JavaScript libraries.

Ambient declaration files are saved with .d.ts extension.

Syntax to declare ambient variables or modules:

declare module ModuleName {
}

Syntax to use Ambient files:

/// <reference path = "AmbientFileName.d.ts" />

Example:

Let us consider that we are using a third party js library with following code.
CalcSum.js

var TestVar;  
(function (TestVar) {  
   var Calc = (function () { 
      function Calc() { 
      } 
      Calc.prototype.doSum = function (num1, num2) {
         return num1 + num2;
      }
   }
}

As this is a js file and we still want to use the doSum() function in our TypeScript code with type safety. We can use this by using ambient declaration. Let us create an ambient declaration file.
Calc.d.ts

declare module TestVar { 
   export class Calc { 
      doSum(num1:number, num2:number) : number; 
   }
}

Now we have to include the above ambient declaration into our typescript file.
CalcTest.ts

/// <reference path = "Calc.d.ts" /> 
var obj = new TestVar.Calc(); 
console.log(obj.doSum(10,20));


Please Share