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 can’t rewrite it in TypeScript. Ensuring Type Safety 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): TutorialSpots.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 = "TutorialSpots.d.ts" />
Example
Assume you been given a third party javascript library which contains code similar to:
File: TutorialSpots.js
"use strict"; var TutorialSpots; (function (TutorialSpots) { var Calc = /** @class */ (function () { function Calc() { } Calc.prototype.doSum = function (limit) { var sum = 0; for (var i = 0; i <= limit; i++) { sum += i; } return sum; }; return Calc; }()); TutorialSpots.Calc = Calc; })(TutorialSpots || (TutorialSpots = {}));
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 TutorialSpots.d.ts
FileName: TutorialSpots.d.ts
declare module TutorialSpots { class Calc { doSum(limit: number): number; } }
Ambient files will not contain the implementations, it is just type declarations. Declarations now need to be included in the typescript file as follows:
FileName : TutorialSpotsTest.ts
/// <reference path = "TutorialSpots.d.ts" /> var obj = new TutorialSpots.Calc() console.log(obj.doSum(5))
After compiling:
Filename: TutorialSpotsTest.js
/// <reference path = "TutorialSpots.d.ts" /> var obj = new TutorialSpots.Calc(); console.log(obj.doSum(5));
Create HTML file: TutorialSpotsTest.html
<html> <body style = "font-size:30px;"> <h1>Ambient Test</h1> <script src = "TutorialSpots.js"></script> <script src = "TutorialSpotsTest.js"></script> </body> </html>
Compiling to .d.ts
tsc -d TutorialSpots.ts
You will receive two files: TutorialSpots.js and TutorialSpots.d.js