Tips & Tricks

Validating JavaScript Code With JSDoc Types Annotations

Today’s post is about a nice feature set (many of you have been using for a long time) and its recent improvements. I’m talking about static type checking when type of parameter or variable on the left side of assignment or function return type is explicitly specified in JSDoc annotation. For 5.0 release we’ve supported Google Closure types syntax, so that quite complex situations can be handled more accurately and conveniently.

To start with let’s consider the most basic situation:
@param

Every constructor function “becomes” a type and its name can be referenced inside JSDoc tags.
Array typesArray of elements of some type could also be specified with [] (for example, Point[]).

Return type is checked inside function and when its call result is used somewhere.
Union type

Type checking may even be helpful without explicit types annotations.

And this is my favorite case. You can specify callback’s ‘this’ and parameter types, and they will be known in passed anonymous function. Note that completion processor uses nearly the same info as type checking, so if type is specified in JSDoc annotation, properties of that type will be shown in completion list.

You can always change the type mismatch highlighting style in Settings | Inspections | JavaScript | General | Type mismatch problem to get it more emphasized or disable it at all.

Develop with pleasure!
– JetBrains Web IDE Team

image description