Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 48 ยท Protocols, Errors and Tooling

Typespecs, Dialyzer and Documentation

Learn Elixir @type and @spec typespecs, @moduledoc and @doc documentation, doctests, ExDoc, Dialyzer basics and how the compiler's new set-theoretic types fit in.

Elixir is dynamically typed: a variable can hold anything, and mistakes show up when code runs. That does not mean you cannot describe your types. Typespecs are annotations (@type and @spec) that document what your functions accept and return. They help readers, power editor hints, feed the documentation generator, and let a tool called Dialyzer find some bugs before you run the program.

The same module attributes carry your documentation: @moduledoc and @doc hold text that appears in IEx and on hexdocs-style web pages, and examples inside them can run as tests (doctests). This lesson covers all of it, then looks at the type checking that the Elixir compiler itself is gaining. It builds on functions and modules.

Elixir is not installed on this site, so the Elixir code here is read-only. The TryIts are JavaScript stand-ins: a tiny runtime type check that mimics what a spec describes, and a doctest runner that mimics the idea of iex> examples. Real Elixir typespecs are not checked at runtime.

Writing a @spec

A spec goes right above the function and has the form name(argument types) :: return type:

ELIXIR
defmodule Temperature do
  @spec celsius_to_fahrenheit(number()) :: float()
  def celsius_to_fahrenheit(c), do: c * 9 / 5 + 32

  @spec describe(number()) :: String.t()
  def describe(t) when t < 0, do: "freezing"
  def describe(_), do: "above freezing"
end

Specs are not enforced at runtime. If you call describe("hot"), Elixir does not check the spec; the guard simply fails and you get a FunctionClauseError. A spec is a promise you write down, which tools can compare against what the code really does.

The built-in types

Type Meaning
integer(), float(), number() Numbers; number() is either
pos_integer(), non_neg_integer(), neg_integer() Integers in a range
boolean(), atom(), nil Booleans, any atom, and the atom nil
binary(), String.t() A binary; String.t() is the type for UTF-8 strings
list(), [integer()] Any list; a list of integers
tuple(), {:ok, integer()} Any tuple; a tuple with a fixed shape
map(), %{name: String.t()} Any map; a map with required keys
keyword(), [{atom(), term()}] A keyword list
any(), term() Any value (they mean the same)
none(), no_return() Never returns, for example because it always raises
pid(), module(), fun() A process id, a module name, a function

Types combine with | (union). Literal atoms and values are types too:

ELIXIR
@spec fetch_user(integer()) :: {:ok, map()} | {:error, :not_found}
@spec color(atom()) :: :red | :green | :blue
@spec first([a]) :: a | nil when a: term()

The last line uses a type variable a, introduced by when a: term(), to say that the result has the same type as the list's elements.

What typespecs are for

Readers Types explain a function in one line.
Tools Editors and Dialyzer use them.
Docs ExDoc shows them on every page.

Typespecs are not checked while your program runs.

1 / 2

Defining your own types

@type names a type so specs stay short and meaningful. A struct usually gets a t() type, which is the convention other code relies on:

ELIXIR
defmodule Account do
  @enforce_keys [:owner]
  defstruct [:owner, balance: 0]

  @type t :: %__MODULE__{owner: String.t(), balance: non_neg_integer()}
  @type result :: {:ok, t()} | {:error, :insufficient_funds}

  @spec deposit(t(), pos_integer()) :: t()
  def deposit(%__MODULE__{} = account, amount) do
    %{account | balance: account.balance + amount}
  end

  @spec withdraw(t(), pos_integer()) :: result()
  def withdraw(%__MODULE__{balance: b} = account, amount) when amount <= b do
    {:ok, %{account | balance: b - amount}}
  end

  def withdraw(_account, _amount), do: {:error, :insufficient_funds}
end

There are three flavors: @type is public (other modules can use Account.t()), @typep is private to the module, and @opaque is public by name but its internals are hidden, so other modules may pass the value around but should not look inside it. Use @opaque for values you want callers to treat as a black box.

Callbacks of behaviours use the same type syntax in @callback.

JS A spec as a runtime check, JavaScript stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Documentation: @moduledoc and @doc

Documentation is plain Markdown stored in module attributes. It is available at runtime (the h helper in IEx shows it) and rendered by ExDoc:

ELIXIR
defmodule Temperature do
  @moduledoc """
  Helpers for converting between temperature scales.
  """

  @doc """
  Converts degrees Celsius to degrees Fahrenheit.

  ## Examples

      iex> Temperature.celsius_to_fahrenheit(100)
      212.0

      iex> Temperature.celsius_to_fahrenheit(0)
      32.0
  """
  @spec celsius_to_fahrenheit(number()) :: float()
  def celsius_to_fahrenheit(c), do: c * 9 / 5 + 32

  @doc false
  def internal_helper, do: :ok
end

A few conventions: the first line of a doc is a one-sentence summary, because lists show only that line. Headings use ##. Code examples are indented four spaces. @doc false hides a public function from the generated docs (use it for functions that must be public but are not part of your API), and @moduledoc false does the same for a module. In IEx, h Temperature.celsius_to_fahrenheit prints the docs, and t Account prints a type.

Doctests

Lines starting with iex> inside a @doc are examples, and the line after each is the expected result. A test file turns them into real tests with one line:

ELIXIR
defmodule TemperatureTest do
  use ExUnit.Case, async: true
  doctest Temperature
end

Running mix test then executes every iex> example and compares its result. This keeps documentation honest: an example that stops being true fails the build. Separate independent examples with a blank line (each blank-line group is its own test), and use ...> for continuation lines. Doctests are best for small, deterministic, pure examples. For anything with side effects, write a normal test (testing with ExUnit).

JS A tiny doctest runner, JavaScript stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

ExDoc: documentation websites

ExDoc turns your @moduledoc, @doc, @type and @spec into a searchable HTML site, the same format used for the standard library and for Hex packages. Add it as a development-only dependency in mix.exs, then fetch and generate:

ELIXIR
defp deps do
  [
    {:ex_doc, "~> 0.34", only: :dev, runtime: false}
  ]
end
TEXT
mix deps.get
mix docs

The result lands in the doc/ folder. Packages published to Hex get their documentation hosted automatically. The version number in the snippet is only an example, so use the current one when you add it. The project layout and mix.exs are covered in Mix: Creating and Managing Projects.

Dialyzer: finding contradictions

Dialyzer (from Erlang, "DIscrepancy AnaLYZer for ERlang programs") analyzes compiled code and reports places where it can prove something is wrong. It uses success typing: it infers what each function can possibly accept and return, and warns only when your code and specs conflict with that, for instance calling a function with an argument it can never handle, or a spec that no clause can satisfy. If Dialyzer cannot prove a problem, it stays quiet, so a clean run does not mean the code is correct, and warnings are real contradictions rather than style opinions.

The community wrapper Dialyxir makes it practical:

ELIXIR
{:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false}
TEXT
mix dialyzer

The first run builds a PLT (persistent lookup table) of types for Erlang, Elixir and your dependencies, which takes several minutes and is cached afterwards. Later runs only analyze your changes. Typical messages say a function "has no local return" (it always crashes), that a call "will never return since the success typing is ...", or that a spec disagrees with the code. Many teams run mix dialyzer in continuous integration.

Types inside the compiler

Dialyzer is a separate tool that sits beside the language. Recent Elixir releases have started adding a gradual, set-theoretic type system to the compiler itself. Starting with the 1.17 series, the compiler infers types for patterns and expressions and reports a growing list of definite errors as ordinary compile warnings (such as comparing or matching values that can never be equal, or calling a function with an argument of the wrong type), with later releases extending the checks to more constructs. You do not have to write any annotations for these checks to help you.

"Gradual" means the system never rejects programs it cannot reason about, and "set-theoretic" means types are treated as sets of values with union, intersection and negation. The practical advice: keep writing @spec and @type for documentation and Dialyzer, upgrade Elixir regularly to benefit from the compiler's checks, and read the release notes of the version you use to see exactly what is checked, because this area is evolving quickly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Are @spec annotations checked while the program runs?

    Specs are metadata. A wrong call fails only if the function itself cannot handle it, for example with a FunctionClauseError.
  2. 2. What is the convention for the type of a struct defined in a module?

    A type named t() in the module is the convention, so other code writes Account.t() in its specs.
  3. 3. What does a doctest do?

    Add doctest MyModule to an ExUnit test module, and each iex> example becomes a test.
  4. 4. What does Dialyzer report?

    Dialyzer uses success typing and only warns when it is sure of a problem, so no warning does not prove correctness.

Summary

  • @spec describes a function's argument and return types; @type, @typep and @opaque define named types, and t() is the convention for a module's struct.
  • Typespecs are not enforced at runtime; they document, power editors, and feed Dialyzer and ExDoc.
  • @moduledoc and @doc hold Markdown documentation, shown by h in IEx and rendered by ExDoc.
  • iex> examples in docs become tests with doctest Module.
  • Dialyzer (via Dialyxir) uses success typing and reports only provable contradictions; the first run builds a PLT.
  • The compiler is gaining gradual set-theoretic type checking in recent releases, with no annotations needed; check the release notes for current coverage.

Next, organize all of this into a real application: Mix: Creating and Managing Projects.