When Specifications Are Used

Elixir type specifications come from Erlang. It is very common to see Erlang code where every exported (public) function is preceded by a -spec line. This is metadata that gives type information. The following code comes from the Elixir parser (which is [currently] written in Erlang). It says the return_error function takes two parameters, an integer and any type, and never returns.

 -spec return_error(integer(), any()) -> no_return().
 return_error(Line, Message) ->
  throw({error, {Line, ?MODULE, Message}}).

One of the reasons the Erlang folks do this is to document their code. You can read it inline while reading the source, and you can also read it in the pages created by their documentation tool.

The other reason is that they have tools such as dialyzer that perform static analysis of Erlang code and report on some kinds of type mismatches.[41]

These same benefits can apply to Elixir code. We have the @spec module attribute for documenting a function’s type specification; in IEx we have the s helper for displaying specifications and the t helper for showing user-defined types. You can also run Erlang tools such as dialyzer on compiled Elixir .beam files.

However, type specifications are not currently in wide use in the Elixir world. Whether you use them is a matter of personal taste.