2

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!

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

But is that available for everyone who downloads the library or do they have to have it installed too? Or am I thinking about it wrong and it needs to be imported into my library?
Basically when someone installs and requires a library it gets the "main" file or index.js file, now if that file has these jsdoc comments intact it should work.
Thanks, that was exactly what I was looking for!
The website you linked is stolen by what seems to be some Hindu gambling business, please update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.