简体   繁体   中英

Define object type for function parameter / get auto completion in VS Code

I am just getting started with JavaScript (using node) and I use VS Code as my editor. I have an object collection for which VS Code offers me auto completion for the method names. However, I pass this object to a function myFunction . Inside the myFunction body I get no auto completion for collection.

While I can understand that, I am wondering how I can fix this. Can this be fixed with JavaScript or do I already need TypeScript for that?

// Get the documents collection
collection = db.collection('myCollection');

// typing "collection." here I get auto completion and can
// e.g. select collection.insertOne
myFunction(collection)

function myFunction(collection) {
  // no auto completion here when typing "collection."
  // (at least it doesn't show collection.insertOne)
  // how to get auto completion here? Do I need TypeScript for that?
  // or is it possible with JavaScript?
}

在此处输入图像描述

Hi this can be easily solved by doing something like

 /**
 * 
 * @param {string[]} collection
 */
function myFunction(collection) {

}

This is called jsDoc and can be very useful when it comes to javascript. You can also use it within the function for simmilar effect as an example

   /**
   * 
   * @type {number}
   */
  const aNumber = 5;

As you can see for my first case in this screen shot在此处输入图像描述 i get auto completion as if my collection is a string array. What ive shown here is some really simple types but you get the idea of how this works. Also jsDoc is very good for commenting your code such as input params and return params and so on.

Also for clarity sake i have included a screenshot of a more complex autocompletion with vs code.

The example is to use electron's 'app' within a function and get auto completion same way you want for collection

在此处输入图像描述

On the contrary this is what happens if i omit the jsdoc

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM