@@ -28,7 +28,7 @@ defmodule TypedStruct do
2828 @type t() :: %__MODULE__{
2929 name: String.t(),
3030 age: non_neg_integer() | nil,
31- happy?: boolean() | nil ,
31+ happy?: boolean(),
3232 phone: String.t() | nil
3333 }
3434 end
@@ -37,7 +37,8 @@ defmodule TypedStruct do
3737
3838 * the keys are present in both the `defstruct` and type definition,
3939 * enforced keys must also be written in `@enforce_keys`,
40- * if a key is not enforced, the type should be nullable.
40+ * if a key has no default value and is not enforced, its type should be
41+ nullable.
4142
4243 If you want to add a field in the struct, you must therefore:
4344
@@ -154,7 +155,7 @@ defmodule TypedStruct do
154155 [line: 5], []},
155156 nil
156157 ]},
157- with_default: {:|, [], [{: integer, [line: 6], []}, nil ]}
158+ with_default: {:integer, [line: 6], []}
158159 ]
159160
160161 ## What do I get?
@@ -209,29 +210,22 @@ defmodule TypedStruct do
209210 # Becomes
210211 defstruct name: "John Smith"
211212
212- The type itself remains the same.
213+ When set to `true`, the `enforce` option enforces the key by adding it to the
214+ `@enforce_keys` attribute.
213215
214- The `enforce` option, when set to `true`, enforces the key. Therefore, the
215- type is not nullable anymore:
216+ field :name, String.t(), enforce: true
216217
217- defmodule Example do
218- use TypedStruct
219-
220- typedstruct do
221- field :name, String.t(), enforce: true
222- end
223- end
224-
225- becomes:
218+ # Becomes
219+ @enforce_keys [:name]
220+ defstruct name: nil
226221
227- defmodule Example do
228- @enforce_keys [:name] # :name is enforced
229- defstruct name: nil
222+ In both cases, the type has no reason to be nullable anymore by default. In one
223+ case the field is filled with its default value and not `nil`, and in the other
224+ case it is enforced. Both options would generate the following type:
230225
231- @type t() :: %__MODULE__{
232- name: String.t() # Not nullable
233- }
234- end
226+ @type t() :: %__MODULE__{
227+ name: String.t() # Not nullable
228+ }
235229 """
236230
237231 @ doc false
@@ -304,9 +298,10 @@ defmodule TypedStruct do
304298
305299 default = opts [ :default ]
306300 enforce? = ! ! opts [ :enforce ]
301+ nullable? = ! default && ! enforce?
307302
308303 Module . put_attribute ( mod , :fields , { name , default } )
309- Module . put_attribute ( mod , :types , { name , type_for ( type , enforce ?) } )
304+ Module . put_attribute ( mod , :types , { name , type_for ( type , nullable ?) } )
310305 if enforce? , do: Module . put_attribute ( mod , :keys_to_enforce , name )
311306 end
312307
@@ -326,6 +321,6 @@ defmodule TypedStruct do
326321 ##
327322
328323 # Makes the type nullable if the key is not enforced.
329- defp type_for ( type , true ) , do: type
324+ defp type_for ( type , false ) , do: type
330325 defp type_for ( type , _ ) , do: quote ( do: unquote ( type ) | nil )
331326end
0 commit comments