File: optional-values.html.md

package info (click to toggle)
ruby-dry-types 1.2.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 504 kB
  • sloc: ruby: 3,059; makefile: 4
file content (35 lines) | stat: -rw-r--r-- 860 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
---
title: Type Attributes
layout: gem-single
name: 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:

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

Add `.optional` and `nil` values become valid:

```ruby
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](docs::extensions/maybe) extension for another approach to handling optional values by returning a [_Monad_](/gems/dry-monads/) object.