TypeScript: Creating .d.ts Files from .js files

TypeScript tutorial: Declaration files

Let’s say you have a simple JavaScript project as follows:

If you want to create .d.ts files from .js files, you can follow the steps below.

index.js

class DemoClass {
  constructor() {}
  printSomething() {
    console.log('this is printing');
  }
  sum(val1, val2) {
    return val1 + val2;
  }
}

package.json

{
  "name": "typescript-dts-from",
  "version": "1.0.0",
  "description": "- https://www.typescriptlang.org/docs/handbook/declaration-files/dts-from-js.html",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^4.7.4"
  }
}

tsconfig.json

{
  // Change this to match your project
  "include": ["src/**/*"],
  "compilerOptions": {
    // Tells TypeScript to read JS files, as
    // normally they are ignored as source files
    "allowJs": true,
    // Generate d.ts files
    "declaration": true,
    // This compiler run should
    // only output d.ts files
    "emitDeclarationOnly": true,
    // Types should go into this directory.
    // Removing this would place the .d.ts files
    // next to the .js files
    "outDir": "dist",
    // go to js file when using IDE functions like
    // "Go to Definition" in VSCode
    "declarationMap": true
  }
}

We just need to run tsc command in the root of the project. This creates the index.d.ts file under the dist folder.

index.d.ts
declare class DemoClass {
    printSomething(): void;
    sum(val1: any, val2: any): any;
}

If you see missing and/or incorrect information in the page, please let us know and we will try to fix it as soon as possible. Thanks!

Related Videos

References

Leave a Reply

%d bloggers like this: