Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • tsc: It stands for TypeScript compiler which is used to invoke the compiler.
  • –declaration: It is a Command Line Interface (CLI) command which emits the TypeScript definition file from the TypeScript (.ts) file.
  • nameOfTypeScriptFile.ts: The TypeScript file which the TypeScript definition file is to be generated from.

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

script.ts




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

script.js




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


  • script.d.ts: This is Generated TypeScript definition file

Javascript




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.

index.ts




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)}`);


index.js




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)));


  • index.d.ts

Javascript




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


Output:



Last Updated : 27 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads