til

How to create .d.ts files from .js files

typescript

You can set up a JavaScript project to emit .d.ts files automatically from JSDoc tags, without having to maintain them manually.

To do so, you have to follow these steps:

  1. Add TypeScript to your devDependencies
  2. Add a tsconfig.json file with this content:
{
  // 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
  }
}
  1. Run the TypeScript compiler to generate the corresponding .d.ts files for JavaScript files.
  2. (optional) Edit package.json to reference the types.

Check here the original article.

I learnt this from @orta