Elixir v1.21 passes all tests in the If-T Type Narrowing Benchmark by Guo et al. This means the release can find more sure bugs in existing Elixir programs. Once type signatures are introduced, narrowing will give more precise types and fewer false positives.

The type system became possible through a partnership between CNRS and Remote. Development work is currently sponsored by Fresha, Supermethod and Dashbit.

Type inference

Elixir performs type inference by refining the dynamic type. This approach differs from how most gradual languages implement inference and typing. In many gradual languages, the dynamic type, often called any, is a black box usable in any context. Consider this Elixir function where x starts with type dynamic because no type signature exists:

def using_x_as_number_and_binary(x) do
  IO.puts x * 2
  IO.puts byte_size(x)
  :ok
end

The program above uses x both as a number (integer or float in x * 2) and as a bitstring in byte_size(x). In some gradual type systems, the checker would accept this program even though it would crash at runtime, because the dynamic type can be used anywhere. In Elixir, the dynamic type can be refined, and the above will report a typing violation: byte_size expects a bitstring but x has type dynamic(float() or integer()).

This works because dynamic() in Elixir actually means dynamic(term()), where term() is the top type. As a variable is used throughout code, its dynamic type is refined by intersecting with the arguments of invoked functions. The process follows these steps: x starts as dynamic(term()), x is given to x * 2, the left operand expects integer() or float(), which intersected with term() gives dynamic(integer() or float()), then x given to byte_size(x) which expects bitstring; the intersection of integer() or float() with bitstring() is empty, causing the violation.

Consider another example:

def using_x_as_integer(x) do
  IO.puts x * 2
  IO.puts rem(x, 2)
  :ok
end

Here x passes to rem, which expects integers. At the function's end, Elixir correctly infers x can only be an integer, because x was refined from dynamic(term()) to dynamic(integer() or float()) and then only to dynamic(integer()). The inferred type for using_x_as_integer is commonly written dynamic(integer()) -> :ok.

All dynamic types in Elixir are refined, so the type system always does its best to find bugs, even with dynamism. The refinement is often precise thanks to reverse arrows, which the article explains next.

Reverse arrows

An arrow is the type of a function: integer() -> boolean() says "given an integer, this function returns a boolean". The left type is the domain (what it accepts), the right is the codomain (what it returns). Every function has arrows, whether from a written type signature or inferred from the function's clauses.

Functions in Elixir can have multiple arrows. Take negate, which negates numbers:

def negate(number) when is_integer(number), do: 0 - number
def negate(number) when is_float(number), do: 0.0 - number

A single arrow type integer() or float() -> integer() or float() is too broad: it says giving an integer may return a float, which never happens. Two arrows give precise types: integer() -> integer() and float() -> float(). This precisely captures that integer in returns integer, float in returns float. Multiple arrows are excellent for functions with multiple clauses, common in Erlang and Elixir.

With this in mind, and remembering rem only works on integers (its type integer(), integer() -> integer()), what is the inferred type of x in:

def negated_remainder(x), do: rem(negate(x), 2)

One might think x is dynamic(integer() or float()), negate's domain. However, x will be inferred to be dynamic(integer()), because Elixir propagates types through arrows in reverse: starts from what the outermost call expects and walks inwards, from results to arguments, until reaching variables.

  • rem(negate(x), 2): rem has a single arrow integer(), integer() -> integer(), so negate(x) must return integer for this to type check.
  • negate(x): negate has two arrows integer() -> integer() and float() -> float(). Since result must be integer, the float arrow can be discarded. The remaining arrow integer() -> integer() means negate's argument must be integer.
  • x itself: x starts as dynamic(term()), then intersected with integer(), resulting in dynamic(integer()).

Inference goes two directions. Going forward, from arguments to results, arrows tell what each call returns. Going in reverse, from results to arguments, arrows tell what each argument must have been for the call to produce the expected result. As precise type signatures get written using multiple arrows, the type system uses those same arrows to infer precise types.

Guards

Now foundation allows understanding how Elixir performs type inference of guards. Take this function clause:

def something(x, y) when is_integer(x) and is_bitstring(y) do
  ...

Both x and y start as dynamic(term()). A guard only succeeds if it returns true. Type signatures (roughly): true, true -> true; true, false -> false; false, true -> false; false, false -> false for and; integer() -> true; not integer() -> false for is_integer; bitstring() -> true; not bitstring() -> false for is_bitstring.

To infer types of when is_integer(x) and is_bitstring(y), start with true (only result for guard success) and propagate it reverse through arrows:

  • and: only arrow returning true is true, true -> true, so both operands must be true.
  • is_integer: only arrow returning true is integer() -> true, so x must be an integer.
  • is_bitstring: only arrow returning true is bitstring() -> true, so y must be a bitstring.

If multiple arrows could return true, simply union their domains. This behaviour is not hardcoded to a handful of functions; it works with any function, in any context.

Type narrowing (occurrence typing)

Occurrence typing refines variable and expression types based on the branch taken in a conditional or pattern match, so the same variable may have different types in different branches.

Example:

if is_bitstring(x) do
  x # x has type: bitstring()
else
  x # x has type: not bitstring()
end

The mechanism is similar to previous sections. Within the do-branch, consider scenarios where is_bitstring(x) returns true. Within else, consider where it returns false.

Since foundation is built on reverse arrows, narrowing also applies to patterns and case-expressions:

def f(x) do
  case parse(x) do
    {:ok, _} -> ... # x is integer()
    :error -> ...   # x is bitstring()
  end
end

parse has no type signature, but Elixir infers arrows from its clauses: integer() -> {:ok, integer()} and bitstring() -> :error. Within the first branch, knowing parse(x) returned a tuple, and the only arrow returning a tuple has integer() as domain, so x must be an integer.

The If-T benchmark evaluates both precision and soundness of type narrowing. Elixir v1.20 already handled 12 of 13 tests but could not infer proper types for this example:

y = is_integer(x)
if y do
  # y is true, x remains dynamic
else
  # y is false, x remains dynamic
end

To narrow x, need to reverse the arrows of is_integer(x). In v1.20, this only happened for the expression given directly to if or case. Here, the expression given to if is the variable y. All v1.20 knew about y is it was a boolean. Inside the do-branch, y is true, but the connection between y and is_integer(x) was lost at assignment, so no arrows to reverse. This would be harmful once type signatures are added, because trivial refactoring like extracting an expression into a variable could lead to false positives.

Elixir v1.21 solves this by keeping track of the expression each variable was assigned to. Now, when y narrows to true, we know y came from is_integer(x), so we continue propagating true reverse through is_integer's arrows, narrowing x to integer(). This works across any number of assignments:

y = is_integer(x)
z = not y
if z do
  # z is true, y is false, x is not integer()
else
  # z is false, y is true, x is integer()
end

Implementation also performs narrowing lazily, by cross-referencing variables in if/case expressions with variables used in each clause, trying to find any assignment they share. If clauses above do not access z, y or x, then no narrowing performed.

Because Elixir defines reverse arrows for almost all operations, it can refine expressions not currently refined in TypeScript, such as data constructors:

def f(foo) when is_bitstring(foo) or is_integer(foo) do
  map = %{foo: foo}
  if is_bitstring(map.foo) do
    byte_size(foo)
  else
    foo + 1
  end
end

Even though foo is set as map value, refining the map still refines the original variable.

Summary

Elixir's approach to type inference and narrowing builds on a few ideas that compose well. Dynamic types are refined as variables are used. Multiple arrows give precise types to functions. Propagating types through those arrows in reverse lets infer and narrow types across conditionals, patterns, and assignments, all without hardcoding knowledge about specific functions.

In Elixir v1.21, these techniques find sure bugs in existing programs without requiring code changes. The same mechanisms apply once type signatures introduced: more precise signatures yield more precise narrowing and fewer false positives.