When to use `required(...)` in typespecs?

Are there circumstances where is required() adds information in typespecs, or is it always 100% redundant?

(Feels like a very silly question :sweat_smile:)

I don’t think it’s silly at all :slight_smile:
Quoting the Typespecs Elixir documentation page:

                                              ## Maps
      | %{}                                   # empty map
      | %{key: value_type}                    # map with required key :key of value_type
      | %{key_type => value_type}             # map with required pairs of key_type and value_type
      | %{required(key_type) => value_type}   # map with required pairs of key_type and value_type
      | %{optional(key_type) => value_type}   # map with optional pairs of key_type and value_type
      | %SomeStruct{}                         # struct with all fields of any type
      | %SomeStruct{key: value_type}          # struct with required key :key of value_type

%{key_type => value_type} is the same as %{required(key_type) => value_type}. So required() can be omitted, but in presence of optional types, it adds a bit of clarity (and IMO when you have many fields it looks better because since it has the same amount of letters as optional, it aligns nicely).

2 Likes

Same here, unless I use optional() I don’t tend to use require().

1 Like

Thank you both for the confirmation.

1 Like