In this post I will show to take advantage of the Closure Compiler's comprehensive typings annotations.
The theory behind this is that the compiler will be able to examine the code, and potentially prevent bugs if it detects type inconsistencies. One example might be passing a string to a function that expects a number.
The Closure compiler takes a different approach to typings. Instead of introducing a new language, types are added through JSDoc tags.
In the first example I will show how to add types when declaring a variable.
In the sample above I used a JSDoc tag called @type to declare a firstName string variable. If I try to assign the variable anything other than a string there will be a compilation error.
In addition to the type we can also declare the variable as a @const. This will prevent the variable from being assigned a value more than once.
Next I will show how to add types to function arguments.
In the following sample I have created a function with two inputs of type number.
Trying to call the function with something that is not of type number will give a compilation error.
We can also declare constructor functions. The JSDoc tag for this is @constructor
Here I have also added a getPersonalInfo function with a return value of type string.
There is also support for annotations on classes:
Classes are similar to constructor functions, but we don't have to add the @constructor annotation.
So far I have been sticking to built-in types like number and string. It's also possible to use custom types.
In the next example I have declared an input to printPerson of type “Person”. This is the same “Person” type I declared above.
The @template annotation is the Closure compiler's way to add support for generics.
Next I have created a generic Adder class. Generic means the class is configurable when it comes to type, instead of hardwired to assume a specific type.
In my example I create two instances of the class, one for numbers, and one for strings.
I have put the samples on Github in case you are interestd in checking them out.