Skip to content

Commit

Permalink
split Type into Decoder / Encoder, closes #336
Browse files Browse the repository at this point in the history
  • Loading branch information
gcanti authored Apr 16, 2020
1 parent e4291df commit af239bd
Show file tree
Hide file tree
Showing 32 changed files with 4,648 additions and 565 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
**Note**: Gaps between patch versions are faulty/broken releases. **Note**: A feature tagged as Experimental is in a
high state of flux, you're at risk of it changing without notice.

# 2.2.0

- **Experimental**
- add `Codec`, `Decoder`, `Encoder`, `Guard`, `Schema`, `Schemable`, `Tree` modules (@gcanti)

# 2.1.3

- **Polish**
Expand Down
60 changes: 60 additions & 0 deletions Codec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

- [Codec interface](#codec-interface)
- [Built-in primitive codecs](#built-in-primitive-codecs)
- [Combinators](#combinators)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

# Codec interface

```ts
export interface Codec<A> extends Decoder<A>, Encoder<A> {}
```

A codec is just a decoder and an encoder packed together.

The following laws must hold

1. `pipe(codec.decode(u), E.fold(() => u, codec.encode) = u` for all `u` in `unknown`
2. `codec.decode(codec.encode(a)) = E.right(a)` for all `a` in `A`

You can build a new codec using the `make` helper

**Example**

```ts
import * as C from 'io-ts/lib/Codec'
import * as D from 'io-ts/lib/Decoder'
import { left, right } from 'fp-ts/lib/Either'

const NumberFromString: C.Codec<number> = C.make(
D.parse(D.string, (s) => {
const n = parseFloat(s)
return isNaN(n) ? left(`cannot decode ${JSON.stringify(s)}, should be parsable into a number`) : right(n)
}),
{ encode: String }
)
```

# Built-in primitive codecs

- `string: Decoder<string>`
- `number: Decoder<number>`
- `boolean: Decoder<boolean>`
- `UnknownArray: Decoder<Array<unknown>>`
- `UnknownRecord: Decoder<Record<string, unknown>>`

# Combinators

- `literal`
- `nullable`
- `type`
- `partial`
- `record`
- `array`
- `tuple`
- `intersection`
- `sum`
- `lazy`
Loading

0 comments on commit af239bd

Please sign in to comment.