DEV Community

Jorrit
Jorrit

Posted on

5 3

JsDoc to TypeScript declaration.

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more