In io-ts, a codec is a value of type Type<A, O, I> that represents the runtime version of a static type A.
It provides four primary capabilities:
- Decoding: Converts inputs of type
I to type A via the decode method. - Encoding: Converts outputs of type
A to type O via the encode method. - Type Guarding: Acts as a TypeScript type guard via the
is property. - Validation: Validates if a value of type
I can be decoded to A via the validate method.
Decoding returns an Either type from fp-ts. By convention, Right represents success and Left represents failure.
class Type<A, O, I> {
constructor(
/** a unique name for this codec */
readonly name: string,
/** a custom type guard */
readonly is: (u: unknown) => u is A,
/** succeeds if a value of type I can be decoded to a value of type A */
readonly validate: (input: I, context: Context) => Either<Errors, A>,
/** converts a value of type A to a value of type O */
readonly encode: (a: A) => O
) {}
/** a version of `validate` with a default context */
decode(i: I): Either<Errors, A>
}