While Elixir is dynamically typed, we can supply optional
typespecs to make sure
our programs are type-safe.
Preventing type errors ensures that there’s no discrepancy between differing types of our program’s constants,
variables, and functions.
Typespecs are also useful as documentation.
Here’s a simple example:
@spec to specify the type of the input and its return value in the
@spec <method name>(<type of parameter>) :: <type of return value>
In the example above, our method
say takes in a
string and returns a
Elixir provides many built-in types. You can also declare your own custom domain-specific types that can then be re-used in other modules.
What happens if the implementation doesn’t match the spec? Let’s modify our code:
Typespecs are not used by the compiler, so if you compile and run this code,
you’ll receive no warnings and the code will run. To perform type checking,
You can set up Dialyzer by installing dialyxir globally, and using the generated
pltas your default
Let’s perform some type checking:
Dialyzer caught our type error. We can fix it and check again:
In production, we can run dialyxir on our project directory, which handles automatic compilation of our Elixir code. We can also set up git hooks to ensure that all type violations are fixed prior to making/pushing commits and reap the full benefits of static analysis.