简体   繁体   中英

Adding variable type declarations and autocompletion in Node / VS Code

I am making a npm library at the moment and was wondering how other people implemented the autocompletion and variable type declarations in VS Code.

For example I can type httpconnection.addListener( and I get a popup that tells me that the first argument is of type event, the second argument is of type function void and so on.

This also works for functions that need to be passed an object, like mysql.createConnection({}); . If I press CTRL + Spacebar, I now know what properties this object has to have and what properties it can have.

I know that JavaScript is dynamically typed and doesn't have fixed type declarations but rather does the conversion at runtime but how do these other people achieve that?

I have tried to add variable types by using the typescript brackets ( variable<Object> ) and something else I found somewhere ( variable?: Object ) but both didn't work.

I least want the autocomplete to show people what properties / attributes they must and what properties they can enter and of what type they should be.

How do I achieve that? Can I just convert the JS file to a TS file and publish it on npm without problems?

Thanks in advance!

One thing you can do is use JSDOCs , atleast that's what I do.

Like for functions I add like,

/**
 * @param {string} somebody
 */
function sayHello(somebody) {
    alert('Hello ' + somebody);
}

Or maybe add one before variable diclaration

/**
 * @type {[]}
 */
const x = someRequiredVariable

You can use custom ES6 classnames as type, not just primitive ones.

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