How to indicate that a variable is an Express object using Javascript Docs?

Asked

Viewed 55 times

1

I’m using the consign to automatically include routes in an application built with Express. In a given file I have the route:

module.exports = app => {
    app.post('/users', (req, res) => {
        //...
    })
}

But this approach, at least for me, resulted in the loss of Javascript Intellisense autocomplete in VS Code.

It would be possible using Javascript documentation tags to instruct the IDE/Editor, in this case VS Code to understand that app is an object of the Express, leading the same to "reactivate" the Intellisense? How could this be done?

1 answer

2


It is possible, if you create an annotation with the type of this variable.

Intellisense accepts Jsdoc annotations to indicate the type of the variable with the following syntax:

/** 
 * @param { string } arg1
 * @param { boolean } arg2
 */
function minhaFuncao(arg1, arg2) {

}

From this model, you can check in the module index.d.ts Express, that kind of his app, is Express, soon you can create an indication for your type app with:

/** @param { import('express').Express } app */
module.exports = app => {
  app.post('/users', (req, res) => {
    // ...
  })
}

From there, Intellisense knows the type of app, and then also recognizes the signature of the method post, also recognizing the type of arguments req, res and next.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.