Sv443
Sv443

Reputation: 749

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!

Upvotes: 2

Views: 1925

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

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.

Upvotes: 4

Related Questions