Ambient declarations are a way of telling the TypeScript compiler that the actual source code exists elsewhere. When you are consuming a bunch of third party js libraries like jquery/angularjs/nodejs you cant rewrite it in TypeScript. Ensuring typesafety and intellisense while using these libraries will be challenging for a TypeScript programmer. Ambient declarations help to seamlessly integrate other js libraries into TypeScript.
Defining Ambients
Ambient declarations are by convention kept in a type declaration file with following extension (d.ts)
Sample.d.ts
The above file will not be transcompiled to JavaScript. It will be used for type safety and intellisense.
The syntax for declaring ambient variables or modules will be as following −
Syntax
declare module Module_Name {
}
The ambient files should be referenced in the client TypeScript file as shown −
/// <reference path = " Sample.d.ts" />
Example
Lets understand this with help of an example. Assume you been given a third party javascript library which contains code similar to this.
FileName: CalcThirdPartyJsLib.js
var TutorialPoint;(function(TutorialPoint){var Calc =(function(){functionCalc(){}
Calc.prototype.doSum=function(limit){var sum =0;for(var i =0; i <= limit; i++){
Calc.prototype.doSum=function(limit){var sum =0;for(var i =0; i <= limit; i++){
sum = sum + i;return sum;return Calc;
TutorialPoint.Calc = Calc;})(TutorialPoint ||(TutorialPoint ={}));var test =newTutorialPoint.Calc();}}}}}</code></pre>
As a typescript programmer you will not have time to rewrite this library to typescript. But still you need to use the doSum() method with type safety. What you could do is ambient declaration file. Let us create an ambient declaration file Calc.d.ts
Ambient files will not contain the implementations, it is just type declarations. Declarations now need to be included in the typescript file as follows.
In order to execute the code, let us add an html page with script tags as given below. Add the compiled CalcTest.js file and the third party library file CalcThirdPartyJsLib.js.
Leave a Reply