Enforcing a type spec

  @spec foo (arg1 :: String.t(), arg2 :: String.t(), arg3 :: float) :: float

  def foo("bing", "bang", "bow") do
      some process
  end

Is there a way to get iex to raise a type spec error for foo() when it’s executed with incorrectly typed argumens?

No. There are others libraries that may help you with that, but “bare” Erlang (and Elixir) do not have support for something like that.

1 Like

Gotcha. Which would you recommend?

TypeCheck is a thing, not sure if it works in IEx. That’s an interesting thought for the library I’m working on, which is compile-time type inference, so I think I’ll toss it on the issues/features list.

2 Likes

If you want static analysis, you can take a look at https://hexdocs.pm/dialyzex/Mix.Tasks.Dialyzer.html

1 Like

Typespec is just annotation and not used at runtime (like @doc).

To raise an error at runtime - you may add guard to functions so that you get no match found error. There are a few libraries to add abstraction for generating typespec and guard…

See also:

(you can see people in this thread there!)

1 Like

This worked out nicely:

iex(2)> Sandbox.foo("bing", "bang", "bow")
** (TypeCheck.TypeError) The call `foo("bing", "bang", "bow")` does not adhere to spec `foo(binary(),  binary(),  float()) :: float()`. Reason:
  parameter no. 3:
    `"bow"` is not a float.
    (arbit 0.1.0) lib/Sandbox.ex:1: Sandbox.foo/3