Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 7 — Gradual Typing

Erlang gave you Dialyzer’s success typings. Elixir is now building something more ambitious: a set-theoretic, gradual type system built into the compiler — inference first, annotations optional. Gradual typing has landed incrementally since Elixir 1.17 and matured through the 1.19/1.20 lines; this chapter was verified against 1.20.3 and re-verified on 1.20.4. The official “Typespecs reference” page documents the annotation syntax; this chapter focuses on the workflow.

Version gating matters here. 1.17 checked patterns against types inferred within the same function. 1.18 added inference across function calls and for tuples/lists/return values. 1.19 added guard-derived types. 1.20 is mature. The examples below assume 1.19+; on 1.17/1.18 you get the same-function warnings but not the cross-function and guard ones.

From Erlang you know: Dialyzer’s success typings and this are answers to the same question — “which arguments can this function actually be called with?” — with two structural differences worth holding onto. Dialyzer is a separate post-hoc pass over a whole-project PLT, so it reports only at analysis time, on success typings, and every finding is a plausibility claim it cannot prove. The built-in checker is part of mix compile, so findings arrive while you edit; it reports only provable violations; and untyped code is not “unchecked” so much as dynamic() — a region of deliberate uncertainty rather than a hole in coverage. Keep running both. They fail differently.

7.1 Set-Theoretic Types in One Minute

Traditional type systems ask: “What single named type is this value?”

Set-theoretic typing asks: “What set of values can this expression represent?” Sets compose with standard operations:

A ∪ B       union           (integer() or binary())
A ∩ B       intersection    (a map that has :id AND is not nil)
¬A          negation        (anything except nil)
A \ B       difference      (integer minus {0})

This models real data shapes directly and describes relationships between values — not just categories.

Set Operations in the Wild

You already reason this way in Erlang — the vocabulary is new, the algebra is not:

ConstructSet reading
integer() | binary() in a specunion — accept either set
Guard is_integer(x) on a clauseintersection — narrows the input set
Multiple function clausesunion of each clause’s accepted input set
:error | {:ok, t}tagged disjoint union — same convention as Erlang

Negation is the operation Dialyzer never gave you directly. The checker uses complements internally to justify exclusions — when it reports that a value “cannot be nil” at a call site, it derived ¬nil from the paths reaching there.

One thing to know before you read your first warning: the syntax the compiler prints is not the syntax you write. Diagnostics use the set-theoretic keywords — you will see dynamic(:many or :one or :two) — but the annotation language is still classic typespecs. Verified on 1.20.4: writing or, and, or not in a @spec/@type is a Kernel.TypespecError, because those are resolved as ordinary remote types (or/2 undefined).

# what you write — classic typespecs, all valid
@spec fetch(String.t() | nil) :: {:ok, term()} | {:error, String.t()}
@spec either(integer() | binary()) :: :ok
@type named :: %{id: pos_integer(), name: String.t()}

# what the compiler prints — set-theoretic, read-only
dynamic(:many or :one or :two)

So negation and intersection are inferred and reported, not hand-writable. That is the honest current state: you describe what you know with |, dynamic(), and maps/structs, and the compiler does the set algebra.

7.2 Gradual Means You Adopt It by Doing Nothing

The codebase splits into zones that coexist:

flowchart TD
    EXIST["Existing Elixir code<br/>(untyped, unchanged)"] --> DYN["dynamic() zone<br/>checker treats values as unknown"]
    EXIST --> PREC["more precisely described code<br/>inferred types · optional @specs"]
    DYN --> SAME["same ecosystem · same compile step<br/>no separate analysis pass"]
    PREC --> SAME
  • Untyped code keeps working; its values are typed dynamic().
  • The checker infers types from your code without annotations.
  • It reports only verified bugs — inputs guaranteed to fail at runtime if executed.
  • Add annotations where you want stronger guarantees.

7.3 Seeing It Work

Sixty seconds, zero annotations. Create a scratch project and paste the examples below into lib/:

mix new typing_demo
cd typing_demo
# write Example 1 to lib/example1.ex …
mix compile      # watch the type-checker report the violation

Example 1 — inferred union flows into an impossible call:

defmodule GradualExample.Example1 do
  def percentage_or_error(value) when is_integer(value) do
    value_or_error =
      if value > 1 do
        value            # integer branch
      else
        "not well"       # binary branch → value_or_error: integer() or binary()
      end

    if value > 1 do
      value_or_error / 100
    else
      String.upcase(value_or_error)
    end
  end

  def input(string) when is_binary(string) do
    percentage_or_error(string)   # ← binary() into integer()-only function
  end
end

mix compile output (excerpt, Elixir 1.20.3):

warning: incompatible types given to percentage_or_error/1:

    percentage_or_error(string)

given types:

    -binary()-

but expected one of:

    integer()

where "string" was given the types:

    # type: binary()
    # from: lib/example1.ex:17:13
    string

    # type: binary()
    # from: lib/example1.ex:17:26
    is_binary(string)

type warning found at:
    │
 18 │     percentage_or_error(string)
    │     ~

Note what happened: no annotations anywhere, yet the checker knew percentage_or_error/1’s guard restricts it to integer() and caught the caller passing binary().

Example 2 — literal atoms as singleton types:

defmodule GradualExample.Example2 do
  def sum(a, b), do: get(a) + get(b)

  def get(:a), do: 1
  def get(:b), do: {:ok, 3}

  def run, do: sum(:a, :b)   # get(:b) returns {:ok, 3} → + on a tuple
end
warning: incompatible types given to sum/2:

    sum(:a, :b)

given types:

    :a, -:b-

but expected one of:

    :a, :a

type warning found at:
    │
  7 │   def run, do: sum(:a, :b)
    │                ~

(The -dashes- mark the offending type in the terminal output.) Each atom literal is its own singleton type, so clause coverage is tracked precisely.

Example 3 — case exhaustiveness through inferred return sets:

defmodule GradualExample.Example3 do
  def num_to_descr(num) do
    case num do
      1 -> :one
      2 -> :two
      _ -> :many
    end
  end

  def print(num) do
    case num_to_descr(num) do
      :zero -> IO.puts("zero")     # ← unreachable: :zero not in result set
      x -> IO.puts("Other: #{x}")
    end
  end
end

Compiling this reports the dead clause with the inferred union:

warning: the following clause will never match:

    :zero ->

because it attempts to match on the result of:

    num_to_descr(num)

which has type:

    dynamic(:many or :one or :two)

Reading a Diagnostic Like a Provenance Trail

The Example 1 warning deserves a slow read — every section is a fact the checker proved:

given types:         binary()       ← what flowed INTO the call
but expected one of: integer()      ← the callee's guard-derived contract
where "string" was given the types:
    # from: lib/example1.ex:20:13   ← where that value was born
    string

This is the structural difference from Dialyzer output: instead of a bare “spec is a supertype of the success typing”, you get a flow trace — declaration site, definition site, call site — across module boundaries. When a warning appears, the interesting question is rarely why but which upstream branch leaked the wrong type in, and the from: lines answer it.

Match Expressions Refine, Not Just Consume

Patterns and guards work symmetrically: branches produce unions going out, patterns narrow types coming in.

defmodule Shapes do
  def describe(shape) do
    case shape do
      {:circle, r} -> {:round, r}      # narrowed to {:circle, integer()}
      {:rect, w, h} -> {:box, w * h}   # narrowed to {:rect, _, _}
      other -> {:unknown, other}       # whatever remains of the union
    end
  end
end

A verified warning appears only when every path into a call fails. Where the value’s type is fully known locally, singletons propagate and the checker reports provably fatal calls:

def down do
  y = 5
  String.length(y)   # ← reported: integer() into binary()-only call
end

But inference across function boundaries keeps dynamic() in the mix whenever any clause admits unknown input — describe/1 above accepts a dynamic other, so its inferred contract lets r stay partly dynamic and a downstream String.length/1 stays silent. That is the gradual contract working as designed: report only what is provably fatal, absorb everything else as dynamic().

7.4 Dialyzer Comparison for Erlang Developers

AspectDialyzerElixir gradual set-theoretic types
AnalysisSuccess typing (post-hoc tool)Built into mix compile
BaselineWhole program, whole-project analysisWhole codebase, on by default — there is no opt-in attribute
Annotations-spec (optional specs)Typespecs, optional; inference needs none
False positivesKnown issue with success typingReports only verified failures
Contracts across modulesSpecsInferred signatures + specs

Keep using Dialyzer during migration — they complement each other. Over time, the built-in checker becomes primary because it runs on every compile with no separate PLT build step.

Known Blind Spots (1.20) — Measured, Not Guessed

Silence is not proof, and the boundary is sharper than you might guess. I ran the same violation — String.upcase/1 given an integer() — through nine shapes on 1.20.4. Reported: direct, case clause, with clause, if branch, and an immediately-invoked fn. Not reported: for comprehension, and any callback handed to Enum.*.

def for_comp,     do: (for i <- [1], do: String.upcase(i))          # SILENT
def enum_map_fn,  do: Enum.map([1], fn v -> String.upcase(v) end)   # SILENT
def enum_map_cap, do: Enum.map([1], &String.upcase/1)               # SILENT
def enum_reduce,  do: Enum.reduce([1], "", fn v, _ -> String.upcase(v) end)  # SILENT
def map_new,      do: Map.new([1], fn v -> {v, String.upcase(v)} end)      # SILENT

def case_clause,  do: (case 1 do v -> String.upcase(v) end)         # reported
def with_clause,  do: (with x <- 1, do: String.upcase(x))          # reported
def if_branch,    do: (if true, do: String.upcase(1))              # reported
def anon_called,  do: (fn v -> String.upcase(v) end).(1)           # reported

So the rule is not “comprehensions and closures.” It is closer to: the checker follows values through language constructs, but not through higher-order boundaries where you pass a function to someone else. The moment a callback crosses into Enum.map/2, the parameter’s type is whatever that function’s spec says — usually dynamic() — and everything downstream of it is unchecked too.

That has a direct practical consequence for how you review code: a violation hidden inside an Enum.* callback is invisible, and pipeline chaining is the dominant Elixir idiom. Annotate the callback boundary yourself when the data comes from outside:

def to_labels(users), do: Enum.map(users, &String.upcase/1)

Annotating that boundary does not help, and that is the single most important thing to know in this chapter. Verified on 1.20.4:

defmodule Callee do
  @spec only_binary(binary()) :: :ok
  def only_binary(_x), do: :ok        # arg unused => body infers dynamic()
end

defmodule Caller do
  def a, do: Callee.only_binary(42)    # an atom, where the spec says binary()
end

mix compile --force is silent. Add a guard so the body constrains the parameter, and the identical call is reported:

def only_binary(x) when is_binary(x), do: :ok
#=> warning: incompatible types given to Callee.only_binary/1
#   given types:       -integer()-
#   but expected one of:  binary()

The rule for 1.20 is blunt: inference drives the checking; @spec is documentation. It will not make a call site fail, and it is not validated against the body either — this compiles clean, spec and body disagreeing about the return type entirely:

@spec liar(integer()) :: :atom
def liar(x), do: x * 2        # returns an integer; spec claims an atom. No warning.

This inverts the Dialyzer instinct. You arrive expecting @spec to be the contract; here it is a comment. Your actual leverage is guards and clauses — is_integer/1, when x > 0, exhaustive multi-clause heads — because those are what inference reads. Type aliases in a spec are worth exactly as much as the guards behind them.

Keep writing @spec for the consumers who benefit (ExDoc, Dialyzer, your own future self). Just do not expect CI to enforce it.

Two more calibration notes:

  • dynamic() on its own means unknown. dynamic(t) is narrower: the runtime value is t or unknown, so you are only warned if no member of t would be accepted.
  • @type t :: %__MODULE__{...} is a classic typespec — it does not make the compiler check your struct’s fields on construction. Typed structs with real field checking are still roadmap work.

Why Success Typings and Gradual Checks Disagree

Dialyzer computes a success typing: for each function, the set of arguments for which execution cannot crash, derived optimistically from the whole program. Optimistic means assumptions — code that looks dead is assumed reachable, so contradictions sometimes surface as warnings that blame correct code. The gradual checker inverts the contract: report only when failure follows from the types on every admitted path, otherwise stay silent (dynamic() absorbs doubt). Fewer guarantees, near-zero noise.

%% Dialyzer's world: optional specs, whole-app analysis, a PLT to build.
-spec percentage(number()) -> number().
percentage(X) -> X / 100.

%% dialyzer --plt ~/.dialyzer_plt --succ_typings myapp

During migration the two disagree productively: Dialyzer finds latent bugs in zones the gradual checker still treats as dynamic(), while the compiler catches regressions on every build in zones you have tightened.

7.5 Adoption Playbook (Step-by-Step)

  1. Upgrade to Elixir 1.20+ (mise use elixir 1.20, asdf, etc.).
  2. Run mix compile --warnings-as-errors in CI to freeze current state.
  3. Read each type warning; fix genuine bugs immediately (they’re verified).
  4. Add guards and clauses at public boundaries — this is what the checker reads. Write @spec too, for docs and Dialyzer, but understand it does not enforce anything on its own (§7.4).
  5. Tighten gradually inward; leave glue/UI layers dynamic() longest.

A first annotation, showing the new type syntax alongside classic typespecs:

defmodule Percentage do
  @type result :: {:ok, number()} | {:error, String.t()}

  # Guards refine parameter types — the checker reads them:
  @spec of(non_neg_integer()) :: float()
  def of(value) when is_integer(value) and value >= 0 do
    value / 100          # ← always a float; `/` returns floats (Ch 02)
  end
end

The exciting part is not “Elixir becomes Java/C#.” It is stronger compile-time reasoning while preserving dynamic style.

Typed Structs and Opaque Boundaries

Struct types use the familiar %Module{} syntax; @opaque hides the representation exactly as -opaque does in Erlang headers:

defmodule Account do
  @enforce_keys [:id]
  defstruct [:id, :balance]

  @type t :: %__MODULE__{id: String.t(), balance: number()}
end

defmodule Ledger do
  @opaque t :: {:ledger, list(Account.t())}
end

Callers type against Account.t() and Ledger.t(); only Ledger may pattern-match the tuple inside — the same information-hiding contract you know from Erlang’s -opaque.

Freezing the Baseline in CI

# CI excerpt — fail the build on any new type warning:
mix compile --warnings-as-errors
mix test

Pair this with the playbook above: today’s clean compile becomes tomorrow’s contract. New warnings block merges; legacy dynamic() zones tighten at your own pace, module by module, starting with pure domain logic where inference is strongest.

Explore More

  • Typespecs reference — annotation syntax including the new set-theoretic forms
  • Gradual set-theoretic types — the official design page; read the “type inference” section twice
  • the typing_demo scratch project from §7.3 — break it on purpose: change a guard, watch the checker trace exactly where the incompatible type flows from
  • Dialyzer docs — for comparison; keep both running during migration (§7.4). Dialyzer’s success typing page explains the reference model this chapter contrasts against
  • Exercise idea: take one of your pure modules, delete nothing, and count how many verified warnings plain mix compile surfaces on Elixir 1.20+
  • Exercise idea: reproduce §7.4’s @spec finding. Write a callee with a narrow @spec and a body that infers dynamic(), call it wrongly from another module, and confirm silence. Then add one guard and confirm the warning appears — that difference is the whole chapter in one experiment

Checkpoint

  1. What does dynamic() mean and where does it come from?
  2. Why are reported warnings trustworthy?
  3. What’s the cheapest first step to benefit today?
  4. A function’s @spec says it accepts binary(). A caller passes an integer. Does the build fail? (Hint: it depends on the body, not the spec.)
  5. Where does a type error most often hide, given that case, with, if, and immediately-invoked fn are all checked?
Answers
  1. The type of all untyped values — anything not yet constrained; gradual typing’s escape hatch that lets typed and untyped zones interoperate.
  2. They represent inputs guaranteed to raise/fail at runtime if executed — no speculative warnings.
  3. Upgrade to 1.20+ and just run mix compile — inference starts finding bugs in existing untyped code with zero changes.
  4. Probably not. The checker infers the callee’s contract from its body; a narrow @spec over a body that infers dynamic() buys no caller-side checking, and the spec is not validated against the body either. Add a guard (when is_binary(x)) and the same call is reported. That is §7.4’s central finding — write guards, not specs, if you want enforcement.
  5. Inside a callback passed to a higher-order function: Enum.map/2, Enum.reduce/3, Map.new/2, and for comprehensions. The moment a function crosses into one of those, its parameter types are whatever that function’s own spec says — usually dynamic() — and everything downstream is unchecked.

Next: Chapter 8 — The Compilation Model