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

    Function object

    • 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.

      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()
      });

      userDecoder.decode({ firstName: 'John', lastName: 'Doe', age: 30 }); // Ok<User>

      // All field failures are collected before returning:
      userDecoder.decode({ firstName: 1, lastName: 2, age: 30 });
      // Err({ issues: [
      // { message: '1 is not a valid string', path: ['firstName'] },
      // { message: '2 is not a valid string', path: ['lastName'] }
      // ] })
      // 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()
      });