|
| 1 | +# Combinators |
| 2 | + |
| 3 | +`io-ts-http` currently exports a handful of combinators for `io-ts` codecs. |
| 4 | + |
| 5 | +## `optionalize` |
| 6 | + |
| 7 | +Provides an easy way to define object types with some required and some optional |
| 8 | +properties. It accepts the same props that `type` and `partial` do in `io-ts`, and |
| 9 | +behaves like a combination of the two. It works by figuring out which properties are |
| 10 | +capable of being `undefined`, and marking them as optional. For example: |
| 11 | + |
| 12 | +```typescript |
| 13 | +const Item = optionalize({ |
| 14 | + necessaryProperty: t.string, |
| 15 | + maybeDefined: t.union([t.string, t.undefined]), |
| 16 | +}); |
| 17 | +``` |
| 18 | + |
| 19 | +defines a codec for the following type: |
| 20 | + |
| 21 | +```typescript |
| 22 | +type Item = { |
| 23 | + necessaryProperty: string; |
| 24 | + maybeDefined?: string; |
| 25 | +}; |
| 26 | +``` |
| 27 | + |
| 28 | +This same type could be defined with a combination of `intersection`, `type`, and |
| 29 | +`partial`, however it is much easier to read, especially when combined with the next |
| 30 | +combinator. |
| 31 | + |
| 32 | +## `optional` |
| 33 | + |
| 34 | +Designed to be paired with `optionalize` for readability. It accepts a codec and unions |
| 35 | +it with undefined. Thus: |
| 36 | + |
| 37 | +```typescript |
| 38 | +// typeof Foo = string | undefined |
| 39 | +const Foo = optional(t.string); |
| 40 | +``` |
| 41 | + |
| 42 | +When used with `optionalize` it becomes easy to see which parameters are optional. |
| 43 | + |
| 44 | +## `flattened` |
| 45 | + |
| 46 | +Allows codecs to be defined where properties are flattened on decode and nested on |
| 47 | +encode. To illustrate: |
| 48 | + |
| 49 | +```typescript |
| 50 | +const Item = flattened({ |
| 51 | + first: { |
| 52 | + second: t.string, |
| 53 | + }, |
| 54 | +}); |
| 55 | + |
| 56 | +type DecodedType = { |
| 57 | + second: string; |
| 58 | +}; |
| 59 | + |
| 60 | +type EncodedType = { |
| 61 | + first: { |
| 62 | + second: string; |
| 63 | + }; |
| 64 | +}; |
| 65 | +``` |
| 66 | + |
| 67 | +You can have multiple top-level properties flattened into one object. |
| 68 | + |
| 69 | +```typescript |
| 70 | +const Item = flattened({ |
| 71 | + foo: { |
| 72 | + fizz: t.string, |
| 73 | + }, |
| 74 | + bar: { |
| 75 | + buzz: t.number, |
| 76 | + }, |
| 77 | +}); |
| 78 | + |
| 79 | +type DecodedType = { |
| 80 | + fizz: string; |
| 81 | + buzz: number; |
| 82 | +}; |
| 83 | + |
| 84 | +type EncodedType = { |
| 85 | + foo: { |
| 86 | + fizz: string; |
| 87 | + }; |
| 88 | + bar: { |
| 89 | + buzz: number; |
| 90 | + }; |
| 91 | +}; |
| 92 | +``` |
| 93 | + |
| 94 | +The library tries to statically prevent defining multiple nested properties with the |
| 95 | +same key, but can't in all cases. If this is worked around, then it is undefined |
| 96 | +behavior. |
0 commit comments