Why use typespecs in Elixir ?
I was recently solving one of the exercises in Exercism’s Elixir track and when reviewing one of the existing solutions on this platform, I found a conscious attempt to make use of typespecs for every function defined as part of the solution to that exercise.
Coming from a Ruby background where we don’t have typespecs as we currently have them in Elixir, one of the things that came to my mind was doesn’t writing typespecs come with an overhead of maintaining them whenever a function changes? Are there any other possible advantages to typespecs that I may be missing and which make their usage totally worth it?
In the elixir-lang.org docs they mention that they are used for
declaring typed function signatures, declaring custom data types and for providing static code analysis through tools like Dialyzer.
This information was something to start with but I wasn’t quite convinced as to why should I make a more conscious attempt to write typespecs in all the Elixir functions that I write.
After some asking around, I was eventually sold on the idea of why writing typespecs is totally worth it. I’ve tried to summarise those advantages of using typespecs below -
- They help determine what a function returns at first glance. This can be quite handy when using functions like GenServer.on_start which has relatively more complex return values
- They are a good first thought when considering to change an existing function(for a given requirement) in the context of what a function currently returns and what one would need it to return
- It helps a lot when learning new libraries. The discussion as per the below screenshot can give you a better idea as to how.

- Last but not the least it’s useful for revealing and restricting inputs and outputs of those functions to people using these functions
Credits to clone1018, harfangk and pochen for the above points discussed as part of the #beginners channel on elixir-lang.slack.com
Basically from the above one could infer that how exactly typespecs could be useful in terms of providing better documentation for functions. In case there are more advantages to typespecs that I may have missed mentioning as part of this post, please feel free to drop a comment below and I’d be happy to update the post accordingly.
If you found this post useful, click the💚 below so that other people will see it here on Medium.
P.S. : This just makes me realise if you’re looking for a way to start contributing to an open source Elixir project, adding typespecs may just be the right way to getting started :)
