DEV Community

loading...

Better Javascript Type Autocomplete with JSdoc

henryjw profile image Henry Williams ・2 min read

If you want to skip the lecture and get straight to the code, here's the repo with all of the examples.

Intro

Whether you like types or not, there's no denying that having autocomplete for types in any language is nice since it means we don't have to run the code to know what the object should look like (I'm looking at you, JavaScript).

VS Code, for example, partially solves this problem by automatically importing the type definitions for the any of the libraries you import, if available, behind-the-scenes.

So, whenever VSCode autocompletes your express methods, there's no magic! It's pulling the the DefinitelyTyped definitions behind the scenes.

However, the VSCode (and other editors) solution is limited because many times there's no way for the editor to know, for instance, the types of parameters a function. See example

Type Autocompleted

Type Not Autocompleted

Solutions

There are a few ways to solve this problem. The way you choose will depend on your project requirements, as well as in your preferences and needs.

In-line JSdoc type definition

This approach allows you to define custom definitions in-line. The downside is that the types defined this way can't be reused outside of the file they were defined in.

Imported type definition

This approach allows you to add types from existing NPM modules to your code. To implement this, you'll first have to npm install the appropriate type definitions into your project. For instance, to add express types, you'll need to npm install --save-dev @types/express.
You can find any types you need at DefinitelyTyped.

Conclusion

As I've shown, there are several ways to improve type autocomplete by using JSDoc annotations. Of course, if you need actual type checking you'll need to use a statically typed language like Typescript or a tool like flow.

There are also a few other uses for type annotations that I didn't go into detail in this article. Feel free to check them out in this repo.

References

https://ricostacruz.com/til/typescript-jsdoc
https://jsdoc.app/tags-typedef.html

Discussion

pic
Editor guide