JSDoc & Generic types. Typescript

Anton Krinitsyn
3 min readJul 29, 2019

In this article, I will explain how to use Typescript with JSDoc and show 2 ways to do generic types in your code.

What I am going to show, works with both ES5 and ES6 module. My toolkit is VSCode in default configuration with no extensions.

Generics in JSDoc

@template tag defines generic type. Simple use it as a regular type in JSDoc notation:

Simple function is defined that wraps an argument with a Promise. Template type is defined and then used to describe both argument and return types.

Here is how linter helps us with a function call:

As you can see, result value type is changed based on argument.

Typescript with JSDoc

Have you ever used MomentJS? It has some amazing typing system. Type related hints all over the place. Here is an example. Notice how popup hints help with argument types:

Its works this way because MomentJS source code has typing file called moment.d.ts, which defines all types and describes function arguments using Typescript syntax.

Try to delete definition file from node_modules and local cache, and you have rough time figuring out function argument.

The same is true for any popular and complex library.

Now, let’s move on from MomentJS and implement similar approach with custom module. Say, we need to create a module which contains previously shown selfPromised() function from the example above.

First, create definition file for the module. Module name will be ./useless.js. Definition file is ./useless.d.ts. It describes exported value of useless module.

I show here the simplest example. Typing file is capable of all Typescript features.

Second, we implement module itself:

implementing useless.js

I am using a small trick here. VSCode only searches for typing file with the same name when import happened with require or import keywords. You won’t get any type hints when implementing module, if you do not use this trick. The trick is to define module type explicitly as I did at the first line with the help of JSDoc notation.

With this trick you do not even need to name typing file the same way as a module. If you have several modules that you want to make typing files for, you could define them in one file and separate it with a namespace feature of Typescript.

Here is full implementation of ./useless.js.

Finally, use module in other places and take advantage of type hints:

Generics is quite rare to see. Most of the times, I have noticed them in popular libraries. Although, If you create complex type interactions in reusable code, generic type is good approach to know.

--

--