JSPM

  • Created
  • Published
  • Downloads 6408
  • Score
    100M100P100Q115274F

Package Exports

  • codeco

Readme

Codeco

Lightweight TypeScript-first encoding and decoding of complex objects.

Idea

A value of type Codec<A, O, I> (called "codec") is the runtime representation of the static type A.

A codec can:

  • decode inputs of type I,
  • encode values to type O,
  • be used as a type predicate.
export abstract class Codec<A, O = A, I = unknown> {
  protected constructor(readonly name: string) {}

  abstract is(input: unknown): input is A;
  abstract encode(value: A): O;
  abstract decode(input: I): Either<Error, A>;
}

The Either type represents a value of one of two possible types (a disjoint union):

  • Left meaning success,
  • Right meaning failure.
type Either<TError, TValue> =
  | {
      readonly _tag: "Left";
      readonly left: TError;
    }
  | {
      readonly _tag: "Right";
      readonly right: TValue;
    };

Implemented types

Description TypeScript codec
null null cs.null or cs.nullCodec
undefined undefined cs.undefined
void void cs.void
string string cs.string
number number cs.number
boolean boolean cs.boolean
BigInt bigint cs.bigint
unknown unknown cs.unknown
literal 's' cs.literal('s')
array of unknown Array<unknown> cs.unknownArray
dictionary of unknown Record<string, unknown> cs.unknownDictionary
array of type Array<A> cs.array(A)
any any cs.any
never never cs.never
dictionary Record<string, A> cs.dictionary(A)
record of type Record<K, A> cs.record(K, A)
partial Partial<{ name: string }> cs.partial({ name: cs.string })
readonly Readonly<A> cs.readonly(A)
type alias type T = { name: A } cs.type({ name: A })
tuple [A, B] cs.tuple([ A, B ])
union A | B cs.union([ A, B ])
intersection A & B cs.intersection([ A, B ])
keyof keyof M cs.keyof(M) (only supports string keys)
recursive types cs.recursive(name, definition)
exact types cs.exact(type) (no unknown extra properties)
strict cs.strict({ name: A }) (an alias of cs.exact(cs.type({ name: A })))
sparse cs.sparse({ name: A }) similar to cs.intersect(cs.type(), cs.partial()
replacement cs.replacement(A, altInput)
optional A | undefined cs.optional(A)
  • structural parsing
  • piping
  • linear parsing