Use type annotations in JavaScript

Excerpt

JavaScript is TypeScript - Typescript is JavaScript - to some degree.

Do you prefer Typescript over JavaScript ?

I use both: JavaScript and TypeScript as the difference is getting less important. One topic here is the support by the source code editors, especially VSCode being the most used IDE these days.

In TypeScript the "type sugar was added to JavaScript using declarations like:

let obj: HTMLImageElement = document.querySelector('img#logo');

But the editor is not only taking the type from the TypeScript style declaration but also from the JSDoc comming with variables and functions. By using this additional source VSCode supports HTML types even in JavaScript, not only in Typescript.

If you are a web developer using Visual Studio Code to develop in typescript you are already familiar with the great support on attributes and methods in the autocomplete feature.

Here is the trick to enable this auto-completion also in JavaScript files by using the @type annotations in JSDoc comments before declaring variables and parameters

// @type HTMLTableSectionElement
let tbody = this.querySelector('tbody');
tbody.

function f(/** @type HTMLImageElement */ img) {
  img.
}

Now, when the mouse hovers the variable name you can see the type definition is recognized. Or you add a dot behind the identifier the autocompletion works respecting the type of the variable like in TypeScript.

See also

Tags

JavaScript