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
pipe(codec.decode(u), E.fold(() => u, codec.encode) = u
for allu
inunknown
codec.decode(codec.encode(a)) = E.right(a)
for alla
inA
You can build a new codec using the make
helper
Example
import * as C from 'io-ts/lib/Codec'
import * as D from 'io-ts/lib/Decoder'
import * as E from 'io-ts/lib/Encoder'
import { left, right } from 'fp-ts/lib/Either'
const decoder: D.Decoder<number> = 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)
})
const encoder: E.Encoder<string, unknown> = {
encode: String
}
export const NumberFromString: C.Codec<string, number> = C.make(decoder, encoder)