Class Decoder<T>Abstract

A decoder for T - that knows how to decode a value into a type T or fails with a reason.

Type Parameters

  • T

    type of this decoder's result

Hierarchy (view full)

Implements

Properties

name: string

The name of this decoder (useful for error reporting).

Methods

  • Parameters

    • arg: unknown

    Returns boolean

  • An alias for transform.

    Type Parameters

    • U

    Parameters

    • tranformer: ((decoded) => U)

      transformer function

        • (decoded): U
        • Parameters

          • decoded: T

          Returns U

    Returns Decoder<U>

    a decoder of the transformed value

  • Takes a decoder of U and produces a decoder of the union of T | U.

    Useful for composing decoders that can decode many types.

    Example:

    asString.or(asNumber) // produces a decoder for string | number
    asString.or(asNumber).or(asBoolean)) // produces a decoder for string | number | boolean

    Type Parameters

    • U

    Parameters

    • other: Decoder<U>

      decoder for next type U

    Returns Decoder<T | U>

    A decoder for decoding T | U

  • Similar to decode, but throws an error if decoding fails.

    Parameters

    • arg: unknown

      value to decode

    Returns T

    decoded value

  • Tests if a value can be decoded by this decoder.

    Parameters

    • arg: unknown

      value to test

    Returns boolean

  • Makes it possible to apply some transformation on a decoded value.

    const asInt = asNumber.transform(num => parseInt(num))
    asInt.parse(117.565) // produces 117

    Type Parameters

    • U

    Parameters

    • transformer: ((decoded) => U)

      transformer function

        • (decoded): U
        • Parameters

          • decoded: T

          Returns U

    Returns Decoder<U>

    a decoder of the transformed value

  • Applies an operation that can also fail to this decoder.

    const asInt = asNumber.try(num => {
    if (Number.isInteger(number)) return success(num)
    else return failure("expected integer but got " + num)
    })
    asInt.parse(117.565) // throws error - $root: expected integer but got 117.565

    Type Parameters

    • U

    Parameters

    Returns Decoder<U>

    a decoder

Generated using TypeDoc