DEV Community

loading...

JsDoc to TypeScript declaration.

Jorrit
An always curious, Biker, Coder in the silicon valley of Zeeland, NL.
・2 min read

A small "how to" create d.ts files from javascript JsDoc annotations.

JsDoc

I'm using nvim with a tsserver (within the CoC extension) editing vanilla javascript. I.m.o properly added JsDoc descriptions/annotations completely removes the urge from using TypeScript, omitting a compile step (keep is simple) so I can test/use these scripts directly in Nodejs and the browser.

Now, wouldn't it be nice to create "types.d.ts" files from plain javascript with JsDoc annotations.

However be aware that JsDoc does not support any @import tag/declaration so this only works with 'in' module jsdoc anotation

For that we need:

I have installed it globally (-g) because I use JsDoc in most of my projects.

npm install -g jsdoc
Enter fullscreen mode Exit fullscreen mode

We need a template to convert the generated documentation to a 'Typescript definition' file.

For that we use:

npm install tsd-jsdoc --save-dev
Enter fullscreen mode Exit fullscreen mode

Time to create definition files from javascript by running the following command. Where 'lib' is the folder where my javascript files live and 'types' is the folder where i want to place the types.d.ts file.

  • -t is the template folder
  • -r is the 'source' folder
  • -d is the destination folder
jsdoc -t node_modules/tsd-jsdoc/dist -r lib/. -d types
Enter fullscreen mode Exit fullscreen mode

And now we have to edit the 'package.json' file to point out where the Typescript definition file can be found.
Add the following and you 'r good to go.

"types": "./types/types.d.ts"
"scripts": {
  "types": "jsdoc -t node_modules/tsd-jsdoc/dist -r lib/. -d types"
}
Enter fullscreen mode Exit fullscreen mode

When executing:

npm run types
Enter fullscreen mode Exit fullscreen mode

the types are being generated.

That's it

Discussion (0)

Forem Open with the Forem app