Javatpoint Logo
Javatpoint Logo

TypeScript Ambients Declaration

TypeScript provides the way to safely and easily use existing JavaScript libraries like jquery, angularjs, nodejs, etc. The Ambient declarations allow us to use existing popular JavaScript libraries safely.

Ambient declarations tell the TypeScript compiler about the actual source code (variable/functions/etc) existing elsewhere. If our TypeScript code needs to use a third party library that was written in plain JavaScript libraries like jquery/angularjs/nodejs, we can always write ambient declarations. The ambient declaration describes the types that would have been there and will be written in TypeScript.

Ambients Declaration

Ambient declarations files are saved with the extension (d.ts). A file with extension .d.ts must have the declare keyword prefixed to each root level definition. It makes clear to the author that there will be no code emitted by TypeScript. The author needs to ensure that the declared item will exist at runtime.

Ambient declarations tell the compiler about the actual source code exist elsewhere. If these source codes do not exist at runtime and we try to use them, then it will break without warning.

Ambient declarations files are like docs file. If the source changes, the docs need to be kept updated also. If the ambient declaration file is not updated, then we will get compiler errors.

We cannot transcompiled the above file into JavaScript. The above file will be used for type safety and intellisense.

The ambient variables and methods can be declared by using the declare keyword. The syntax for the ambient declaration is given below.

Syntax

Syntax to access Ambient files:

Example:

The following example can understand the Ambient declaration. Here, we are using a third-party JavaScript library with the following code.

Addition.js

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 doSum() function with type safety, then we can do this by using ambient declaration. Let us create an ambient declaration file.

CalcSum.d.ts

Now, include this ambient declaration file (CalcSum.d.ts) into our TypeScript file.

Main.ts

Compile and executed the Main.ts file by using the following command on the console:

output

We will get the following output.

Sum: 40

Next Topic#




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA