The Ambient declarations in Typescript are used to tell the typescript compiler that the actual code exists somewhere else. The third-party library that is written in plain JavaScript or CoffeeScript like jquery/angularjs/nodejs, while this is needed for our TypeScript use, then we can always write ambient declarations and use them.
Ambient Declaration:
Files extension for Ambient declarations is (d.ts). For each root level definition, a file extension (d.ts) must have the declare keyword to be used in Typescript.
If we try to use the source code which does not exist at runtime, then the program will BREAK without WARNING.
Ambient declarations files are like docs file. The docs need to be kept updated while source changes. Else we will get compiler errors if the Ambient declarations files are not updated.
File.d.ts
We cannot transcompile the above file into JavaScript. The above file will be used for type safety and intellisense.
With the declare keyword, the ambient variables and methods can be declared.
The syntax for the ambient declaration is:
Syntax:
declare module module_name{ }
Syntax to access Ambient files:
Ambient declaration can be understand by following example. Below, we are using a third-party JavaScript library with the following code.
Example:
var TestSum; ( function (TestSum) { var Cal = ( function () { function Cal() { } Cal.prototype.doSum = function (a, b) { return a + b; } }) }) |
As this is a JS file and we will not have time to re-write this library to typescript. But still need to use the doAdd() function with type safety, then we can do this by using ambient declaration. Let us create an ambient declaration file.
declare module TestAdd{ export class Cal { doAdd(a:number, b:number) : number; } } |
Now, include this ambient declaration file (CalAdd.d.ts) into our TypeScript file.
Main.ts
var obj = new TestAdd.Cal(); console.log( "Add: " +obj.doAdd(40, 25)); |
Compile and execute the Main.ts file by using the following command on the console:
$ tsc main.ts $ node Main.js
Output:
We will get the following output.
65