With TypeScript 3.7, TypeScript added support for generating .d.ts files from JavaScript using JSDoc syntax.

This set up means you can own the editor experience of TypeScript-powered editors without porting your project to TypeScript, or having to maintain .d.ts files in your codebase. TypeScript supports most JSDoc tags, you can find the reference here.

Setting up your Project to emit .d.ts files

To add creation of .d.ts files in your project, you will need to do up-to four steps:

  • Add TypeScript to your dev dependencies
  • Add a tsconfig.json to configure TypeScript
  • Run the TypeScript compiler to generate the corresponding d.ts files for JS files
  • (optional) Edit your package.json to reference the types

Adding TypeScript

You can learn how to do this in our installation page.

TSConfig

The TSConfig is a json5 file which configures both your compiler flags, and declare where to find files. In this case, you will want a file like the following:

  1. json
    {
  2. // Change this to match your project
  3. include: ["src/**/*"],
  4. compilerOptions: {
  5. // Tells TypeScript to read JS files, as
  6. // normally they are ignored as source files
  7. allowJs: true,
  8. // Generate d.ts files
  9. declaration: true,
  10. // This compiler run should
  11. // only output d.ts files
  12. emitDeclarationOnly: true,
  13. // Types should go into this directory.
  14. // Removing this would place the .d.ts files
  15. // next to the .js files
  16. outDir: "dist"
  17. }
  18. }

You can learn more about the options in the tsconfig reference. An alternative to using a TSConfig file is the CLI, this is the same behavior as a CLI command.

  1. sh
    npx typescript src/**/*.js --declaration --allowJs --emitDeclarationOnly --outDir types

Run the compiler

You can learn how to do this in our installation page. You want to make sure these files are included in your package if you have the files in your project’s .gitignore.

Editing the package.json

TypeScript replicates the node resolution for modules in a package.json, with an additional step for finding .d.ts files. Roughly, the resolution will first check the optional "types" field, then the "main" field, and finally will try index.d.ts in the root.

Package.jsonLocation of default .d.ts
No “types” fieldchecks “main”, then index.d.ts
“types”: “main.d.ts”main.d.ts
“types”: “./dist/main.js”./main/main.d.ts

If absent, then “main” is used

Package.jsonLocation of default .d.ts
No “main” fieldindex.d.ts
“main”:“index.js”index.d.ts
“main”:“./dist/index.js”./dist/index.d.ts

Tips

  • If you’d like to write tests for your .d.ts files, try tsd