Skip to content

Latest commit

 

History

History
35 lines (25 loc) · 860 Bytes

optional-values.html.md

File metadata and controls

35 lines (25 loc) · 860 Bytes
title layout name
Type Attributes
gem-single
dry-types

Types themselves have optional attributes you can apply to get further functionality.

Append .optional to a Type to allow nil

By default, nil values raise an error:

Types::Strict::String[nil]
# => raises Dry::Types::ConstraintError

Add .optional and nil values become valid:

optional_string = Types::Strict::String.optional

optional_string[nil]
# => nil
optional_string['something']
# => "something"
optional_string[123]
# raises Dry::Types::ConstraintError

Types::String.optional is just syntactic sugar for Types::Strict::Nil | Types::Strict::String.

Handle optional values using Monads

See Maybe extension for another approach to handling optional values by returning a Monad object.