In Typescript, Ambient
in refers to the declarations used to inform a compiler that the actual piece of code exists in a different place. For example, a developer might want to write a third-party library in plain JS using jQuery or Angular. In this situation, they would need to use jQuery, Angular, Node in Typescript, and they would need to use Ambient declaration to access the third-party library.
A few key things to keep in mind:
d.ts
.d.ts
needs to have the declare
keyword included in Typescript for every root-level definition.To declare Ambient methods and variables, use a
declare
keyword.
Let’s look at the syntax for Ambient declaration:
declare module module_name{
}
Let’s look at the syntax used to access Ambient files to make it clearer:
// hello.js
(function (TestDiff) {
var Calculate = (function () {
function Calculate() {
}
Calculate.prototype.doDiff = function (a, b) {
return a - b;
}
})
})
The above file is a .js
. You might not have the time to write this library in Typescript, but you do need to add the doSubtract()
function using Ambient declaration.
// Caclulate.ts
declare module TestDiff{
export class Calculate {
doSubtract(a:number, b:number) : number;
}
}
Make sure to include this Ambient file in the Typescript file:
// Main.ts
var object = new TestDiff.Cal();
console.log("Subtract: " + object.doSubtract(30, 15));
Now, run the following commands:
$ tsc main.ts
$ node Main.js
We will get the following output:
15
Free Resources