TypeScript Ambients or Declaration or Definition files:

In TypeScript the Ambients or Declaration or Definition files are used, when needed to include some external javascript library but at that time of compilation we do not need to convert the file from typescript to javascript and typescript can not understand its syntax also as not its pre defined in typescript and now there is a way that we have to convert all the code of the library into typescript code, but it is very difficult and time-consuming so we needed a definition file where we are going to define the property only of the library file and will do typescript code and we do not need to convert the definition file from TypeScript Code to javascript code as its contents are only the definition of the library and we are including the library javascript file into our HTML project.

To make a Ambients or Declaration or Definition file we have to add .d before the extension .ts so if the filename is sample then the Ambients or Declaration or Definition file name will be sample.d.ts

Now suppose we have an external javascript file called factorial.js and it contains a function that will return the factorial value of a number passed to the function as a parameter.

And the sample js code of the factorial.js is:
"use strict";
function fact(num) {
    if (num <= 0) {
        return 1;
    }
    else {
        return (num * fact(num - 1));
    }
}

Now we have to create an ambient or declaration or definition file suppose called fact.d.ts now in that file we have to create a module followed by declaring keyword and inside the module, followed by export keyword we have to declare the function name as it is in the external javascript file and have to pass the parameters and the return type of the function but does not need to declare all the coding inside the function,

Example of fact.d.ts file
declare module DoFactCalc { 
   export function fact(num:number):number;
}

Now, where you are going to use the function suppose in app.ts file you have to include the module file that is the fact.d.ts file by tiple slash reference and then you can be able to call the function and typescript will not through any error.

Example of app.ts file:
/// <reference path = "./fact.d.ts">
var factResult = DoFactCalc.fact(5);
console.log(factResult);

on compiling it Typescript will generate a file for app.ts and we do not need the fact.d.ts file if you want to run the file from the node it will not going to provide the proper output but while you are going to work on an HTML file including both files factorial.js and app.js it will work properly.

Share The Post On -