What is Ambient in TypeScript?

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.

What is unique about Ambient declaration?

A few key things to keep in mind:

  1. All files for Ambient declarations have the extension d.ts.
  2. File extension d.ts needs to have the declare keyword included in Typescript for every root-level definition.
  3. Any source code that does not exist, but is used at runtime, will break the program.
  4. All Ambient declaration files resemble doc files. These docs require frequent updates in order to overcome compiler errors.

To declare Ambient methods and variables, use a declare keyword.

Let’s look at the syntax for Ambient declaration:

Syntax

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 
Copyright ©2024 Educative, Inc. All rights reserved