Open In App

How to generate TypeScript definition file from any .js file?

A TypeScript definition file or a type declaration file is any TypeScript file that has the .d.ts filename extension. These files are only meant to hold the type declarations of that particular script and not the source code itself. This means that they are not a part of the compilation process. In this article, we will see how to generate a TypeScript definition file from any .js file or any normal TypeScript file.

We enter the following command into the terminal to generate any TypeScript definition file from a .js file:



Syntax:

tsc --declaration nameOfTypeScriptFile.ts

Explanation:



Note: To compile a TypeScript file to a JavaScript file and subsequently execute it, we use the following commands:

tsc nameOfTypeScriptFile.ts
node convertedJavaScriptFile.js

Example 1: The following example has an object literal with two key-value pairs, the first property being name with its corresponding value as “GeeksforGeeks” and the second property being founded with its value being 2009.

script.ts: Generated output TypeScript file




const object = {
    name: "GeeksforGeeks",
    founded: 2009,
};
  
console.log(
    `The organisation is ${object.name} and 
        it was founded in ${object.founded}`
);

script.js: Generated output JavaScript file




var object = {
    name: "GeeksforGeeks",
    founded: 2009
};
console.log("The organisation is ".concat(object.name, 
    " and it was founded in ").concat(object.founded));




declare const object: {
    name: string;
    founded: number;
};

Output:

Example 2: The following example has a user-defined function addTwoNumbers(a,b) which computes the sum of two numbers and returns the result.




function addTwoNumbers(a: number, b: number) {
    return a + b;
}
  
const n1 = 2,
    n2 = 9;
console.log(`The sum of ${n1} and ${n2} 
    is ${addTwoNumbers(n1, n2)}`);




function addTwoNumbers(a, b) {
    return a + b;
}
var n1 = 2, n2 = 9;
console.log("The sum of ".concat(n1, " and ")
    .concat(n2, " is ").concat(addTwoNumbers(n1, n2)));




declare function addTwoNumbers(a: number, b: number): number;
declare const n1 = 2, n2 = 9;

Output:


Article Tags :