ts.data.json - v4.1.0
    Preparing search index...

    Class Decoder<T>

    A decoder that can validate and transform JSON data into strongly typed TypeScript values.

    Let's replicate the string decoder:

    const myStringDecoder = (): JsonDecoder.Decoder<string> => new JsonDecoder.Decoder(
    (json: unknown) => {
    if (typeof json === 'string') {
    return JsonDecoder.ok(json);
    } else {
    return JsonDecoder.err([{ message: 'Expected a string', path: [] }]);
    }
    }
    );
    myStringDecoder().decode('hello'); // Ok<string>({value: 'hello'})
    myStringDecoder().decode(123); // Err({ issues: [{ message: 'Expected a string', path: [] }] })

    Type Parameters

    • T

      The type that this decoder will produce when successful

    Implements

    • StandardSchemaV1<unknown, T>
    Index

    Constructor

    Entry Point

    Transformation

    Constructor

    • Creates a new decoder that can validate and transform JSON data into strongly typed TypeScript values.

      Type Parameters

      • T

        The type that this decoder will produce when successful

      Parameters

      • decodeFn: (json: any) => Result<T>

        A function that takes a JSON object and returns a Result

      Returns Decoder<T>

    Entry Point

    "~standard": Props<unknown, T> = ...

    The Standard Schema interface for this decoder.

    • Decodes a JSON object of type and returns a Result

      Parameters

      • json: any

        The JSON object to decode

      Returns Result<T>

      A Result containing either the decoded value or an error message

      JsonDecoder.string().decode('hi'); // Ok<string>({value: 'hi'})
      JsonDecoder.string().decode(5); // Err({ issues: [{ message: '"5" is not a valid string', path: [] }] })
    • Decodes a JSON object of type and returns a Promise

      Parameters

      • json: any

        The JSON object to decode

      Returns Promise<T>

      A Promise that resolves with the decoded value or rejects with an error message

      JsonDecoder.string().decodePromise('hola').then(res => console.log(res)); // 'hola'
      JsonDecoder.string().decodePromise(2).catch(err => console.log(err.message)); // '2 is not a valid string'
    • Parses a JSON object of type and returns the decoded value or throws an error

      Parameters

      • json: any

        The JSON object to decode

      Returns T

      The decoded value of type T

      Throws an Error whose message describes the failure and whose cause contains the structured DecodingIssue[]

      JsonDecoder.string().parse('hello'); // 'hello'
      JsonDecoder.string().parse(123); // throws Error('123 is not a valid string')

      // The thrown message prefixes each failure with its location, array indices use bracket notation:
      const decoder = JsonDecoder.object({ items: JsonDecoder.array(JsonDecoder.number()) });
      decoder.parse({ items: ['x'] }); // throws Error('items[0]: "x" is not a valid number')

    Transformation

    • Chain together a sequence of decoders that may fail.

      Type Parameters

      • O

      Parameters

      • fn: (value: T) => Decoder<O>

        Function that returns a new decoder

      Returns Decoder<O>

      A new decoder that chains the current decoder with the result of fn

      const adultDecoder = JsonDecoder.number().flatMap(age =>
      age >= 18
      ? JsonDecoder.succeed()
      : JsonDecoder.fail(`Age ${age} is less than 18`)
      );
      adultDecoder.decode(18); // Ok<number>({value: 18})
      adultDecoder.decode(17); // Err({ issues: [{ message: 'Age 17 is less than 18', path: [] }] })
    • If the decoder has succeeded, transforms the decoded value into something else

      Type Parameters

      • O

      Parameters

      • fn: (value: T) => O

        The transformation function

      Returns Decoder<O>

      A new decoder that applies the transformation

      // Decode a string, then transform it into a Date
      const dateDecoder = JsonDecoder.string().map(stringDate => new Date(stringDate));
      // Ok scenario
      dateDecoder.decode('2018-12-21T18:22:25.490Z'); // Ok<Date>({value: Date(......)})
      // Err scenario
      dateDecoder.decode(false); // Err({ issues: [{ message: 'false is not a valid string', path: [] }] })