• Decoder for objects with specified field decoders. Supports mapping a TypeScript property to a different JSON key via a { fromKey, decoder } entry in the decoders map.

    Type Parameters

    • T

    Parameters

    • decoders: DecoderObject<T>

      Key/value pairs of decoders for each object field.

    • decoderName: string

      How to display the name of the object being decoded in errors.

    Returns Decoder<T>

    A decoder that validates and returns objects matching the specified structure

    interface User {
    firstName: string;
    lastName: string;
    age: number;
    }

    const userDecoder = JsonDecoder.object<User>(
    {
    firstName: JsonDecoder.string(),
    lastName: JsonDecoder.string(),
    age: JsonDecoder.number()
    },
    'User'
    );

    const json = {
    firstName: 'John',
    lastName: 'Doe',
    age: 30
    };

    userDecoder.decode(json); // Ok<User>({value: {firstName: 'John', lastName: 'Doe', age: 30}})
    // You can also use `fromKey` to map TypeScript properties to different JSON keys
    const userDecoder = JsonDecoder.object<User>(
    {
    firstName: { fromKey: 'first_name', decoder: JsonDecoder.string() },
    lastName: { fromKey: 'last_name', decoder: JsonDecoder.string() },
    age: JsonDecoder.number()
    },
    'User'
    );