dry-types

v1.8 v1.7
  1. Introduction
  2. Getting Started
  3. Built-in Types
  4. Type Attributes
  5. Default Values
  6. Fallbacks
  7. Constraints
  8. Hash Schemas
  9. Array With Member
  10. Enum
  11. Map
  12. Combining Types
    1. Intersection
    2. Sum
  13. Custom Types
  14. Custom Type Builders
  15. Extensions
    1. Maybe
    2. Monads

TOC

  1. Append .optional to a Type to allow nil
  2. Handle optional values using Monads

Type Attributes

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.