Is it overprotective to have defaults validation with TypedStruct and TypedEctoSchema?

Dear community,

There are lovely TypedStruct by @ejpcmac and TypedEctoSchema by @bamorim libraries to define structs in combination with t() types.

Using them, I missed the validation of default values conformance to t(). That validation seems good because initial default values defining the app’s state can drift from the type definition later as the code evolves. That, in turn, can confuse the local thinking about what’s correctly defined the value or the type?

To address this, I’ve added the compile-time defaults validation feature to the Domo library. That works for any struct that has a t() type defined. And can be activated by adding use Domo like the following:

defmodule Order do
  use TypedStruct
  use Domo

  typedstruct enforce: true do
    field :id, non_neg_integer()
    field :items, [String.t()], default: []

That gives the compile-time error highlighting the issue immediately :smile:

Compiling 1 file (.ex)
Domo is compiling type ensurer for 1 module (.ex)

== Compilation error in file lib/functional_core_struct.ex:55 ==
** A default value given via defstruct/1 in Order module mismatches the type.
"Invalid value nil for field :id of %Order{}. Expected the value matching the non_neg_integer() type."

And adding default: 1 option to field :id or changing its type to non_neg_integer() | nil leads to successful compilation.

How do you see it can be worthful to your projects?


This is extremely useful. I’d use the hell out of it!


Hello @IvanR, thank you for mentioning me here, you’ve just made me aware of Domo :slight_smile: This seems very neat!

I am not writing much code in Elixir these times, doing mainly embedded stuff in Rust at home (and C / Python at work), but be sure I’ll use it on my next projects using Elixir (certainly some Nerves firmware communicating with other embedded systems written in Rust) :slight_smile:

Validating the default values was on my roadmap, but since you’ve solved it in an elegant way and I
want TypedStruct to be thin, can I mention it in the README / docs as a solution for this?


FYI, if you’re interested to learn more about Domo, we’ve recently had @IvanR as a guest in ElixirMix where we talked about Domo:


Hello @ejpcmac,

Thanks for your reply. As the proverb says, the appropriate tool is to be used for the appropriate problem. Sometimes, other languages fit better, and it’d be super good if you use Elixir/Nerves on the other project! :slightly_smiling_face:

I’m glad that you liked the library! :slightly_smiling_face: I was inspired a lot by TypedStruct working on it. And I’ll be delighted if you mention the Domo solution for the default checks in the README/docs.

1 Like

Thanks a lot for having me at ElixirMix back then. It was a very welcoming and good atmosphere during the recording, which I liked very much! I’ll be glad to come again :slightly_smiling_face: