Now, Lets write it using JSDoc specs
Excelente! 👍 You have typehinting in VSCode with the help of JsDoc.
Now, lets write another example with custom data types. Here we'll work with moment JS
Here, we are using @typedef to define custom type definations, in this case type Moment which is provided in the "moment" library and using it in the @param annotation to get type hinting. Notice when I type startDate, it suggest methods coming with a moment object.
Its easy, you just have to know a little bit of TypeScript. Let me show you the directory structure.. It looks like this
┃ ┗ post.controller.js
┃ ┣ post.model.d.ts
┃ ┗ post.model.js
The controller method is utilising PostModel and PostDocument type definations and suggesting the properties that are available.
The interfaces defined in post.model.d.ts defines your types and helps with suggestions. This is very useful because in mongoose static methods and schema properties does not appear normally in suggesions. So from now on you can import any type in your project and utilise it's definations.
Note: In the example of moment js we saw that type definations were provided in the library itself but in case if it is not then chances are you will find the type definations in the npm repository. For example you can install type definations for the bcrypt library on @types/bcrypt
In the moment JS example we passed 2 argument to getDiff function. How do we make sure that when executing this function we only pass 2 moment js object and not anything else. Well, there are 2 ways
Notice how on line #17 VSCode is complaining that the type of the first argument passed is not correct.
You can enable this globally as well in your JS project by toggling
That is it, now you can utilise JSDoc and VSCode together for type hinting. Thanks for reading tutorial. We are hoping to update more tutorials like these very soon.
- Visual Studio Code (IDE)
- JsDoc (API documentation generator)
- Peek (Screen recorder)
- VSCode theme - GitHub Dark Default
Part 2 of this tutorial is updated here - How to use JsDoc annotations with VsCode for intellisense - PART 2 👨💻😎
In part 2 we discuss about @callback, @class, @constructor, @private and @public .
Before you leave, I just want to thank you for reading this article 🖤. Me and my friend started working on our own blog thalava.com
Please visit our blog for more tutorials. We are excited to share more tutorials.
Thanks again, love from thalava.com 🖤