There are several ways of enabling this feature: 1) per file, 2) using a setting or 3) Using a JSConfig (or TSConfig). Let’s examine the most basic and straightforward approach: per file.

By putting // @ts-check comment at the top of the .js document, we opt-in to static type checking. Let’s see this in action.

As evident from the example above, when we firstly put a string into the actor variable, changing it into a boolean variable throws an error — 'true' is not assignable to type 'string' — just like TypeScript would do. Furthermore, if we chose to, we can be more specific. Let’s explicitly declare that the actor variable should be a string.

The type of comment used here is not important; the same can be achieved by using double slashes // @type { string }.

So, the basic syntax for defining a type is a comment just above the variable with the following structure: /** @type { TYPE } */.

But it can get more powerful than just this; remember, this is powered by TypeScript! Let’s say we want to have an array that stores just strings. Here’s how we can do it.

Array didn’t allow us to store an object, because we explicitly stated that we want strings. When addressing objects, we can explicitly define a set of properties as follows.

The same applies for classes, functions (though, in JavaScript, class IS a function, but that’s another story). Here’s what we can do.

Notice how there’s an error, notifying us that when calling super, we need to pass 3 parameters with values of the specified types. Here’s another example.

Note how we defined movies as an array of objects that have id (number), title (string) and genre (array of strings).

Of course, we can use this for defining DOM types as well, e.g.: