Unraveling nested objects using ts.data.json: A step-by-step guide

I'm experimenting with the code example found at https://github.com/joanllenas/ts.data.json to decode and validate a JSON payload in Typescript. While it works fine, my goal is to apply this concept to nested data structures, such as having a User object that contains an Address.

I attempted to define the type for Address using JsonDecoder.object, but I encountered an issue. My IDE (IntelliJ) suggests that I need a DecoderObject instead of a Decoder. Can anyone provide guidance on how to achieve this?

type Address = {
    street: string;
    town: string; 
    postcode: string;
};


type User = {
    firstname: string;
    lastname: string;
    address: Address;
};

const addressDecoder = JsonDecoder.object<User>(
    {
        street: JsonDecoder.string,
        town: JsonDecoder.string,
        postcode: JsonDecoder.string
    },
    'User'
);


const userDecoder = JsonDecoder.object<User>(
    {
        firstname: JsonDecoder.string,
        lastname: JsonDecoder.string,
        address: JsonDecoder.object(addressDecoder, "AddressDecoder")
    },
    'User'
);

Answer №1

Let's start with the basics: in this particular scenario, both decoders share the same name. However, this can be easily rectified.

Regarding your inquiry: once you address the aforementioned issue, you should substitute the address decoder with decoderObject as demonstrated below:

const addressDecoder = JsonDecoder.object<Address>(
    {
        street: JsonDecoder.string,
        town: JsonDecoder.string,
        postcode: JsonDecoder.string
    },
    'Address'
);

const userDecoder = JsonDecoder.object<User>(
    {
        firstname: JsonDecoder.string,
        lastname: JsonDecoder.string,
        address: addressDecoder
    },
    'User'
);

By implementing these changes, I believe it will function correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to substitute the HOC with a single call and solely modify the prop?

One issue I've encountered in my project is the repetitive use of a Higher Order Component (HOC) for the header. Each time it's used, the props are set to determine whether header links should be displayed or not. My objective is to streamline th ...

Is it possible for sibling functions to have the same generic type in common?

Let's consider the functions setup and retrieve: function setup<Data = any>() { // ... } function retrieve<Data = any>(): Data { return 1 as Data } If we execute the setup function: type Item = {name: 'example'} setup< ...

Deciphering intricate Type Script Type declarations

I am seeking clarification on how to utilize the object type for sending headers, aside from HttpHeaders provided in the HTTPClient declaration. While working with Angular HttpClient, I aim to include headers using an Object. However, I am unsure of how t ...

Is it possible to generate assets or files in Angular 4 based on different environments?

Is it possible to generate assets/files on build in our Angular app using environment variables? We are looking to create an 'auth/settings.js' file in the assets folder with client id's and apiUrl's unique to each environment. These v ...

Trouble occurs in the HTML code when trying to access a property from an inherited interface in Angular

Currently, I am working with Angular 17 and have encountered a specific query: In my project, there is an IDetails interface containing certain properties: export interface IDetails { summary: Summary; description: string; } Additionally, there is an ...

Automatically select a value in MUI AutoComplete and retrieve the corresponding object

I recently set up a list using the MUI (v4) Select component. I've received a feature request to make this list searchable due to its extensive length. Unfortunately, it appears that the only option within MUI library for this functionality is the Au ...

Query Parameter Matching in Typescript: Retrieve and output all query parameter values that correspond to a specific parameter

Is there a way to extract all value for a specific query parameter from an URL? For example, if we have a string like ?code1=AF&code1=AE&code1=GE&code3=FW Can we search this string for all values associated with the parameter code1? So, in ...

The pivotal Angular universal service

In my application, I have the need to store global variables that are specific to each user. To achieve this, I created a Service that allows access to these variables from any component. However, I am wondering if there is a way to share this service t ...

Can the output type of a function be dynamically determined by using the function parameter name as the property in an interface?

I am attempting to dynamically assign the output of a function based on the name of the input parameter within an existing interface: interface MyInterface { typeA: string; typeB: boolean; typeC: string; typeD: number; ... } const myFunction: ( ...

Developing with Angular and Firebase: Setting up a new data node

Is there a way to create a new node called terriangen, add a key, and set the object data in Firebase? -usernames -{UID} -mylibrary -{key} -terriangen -{key} type:mountain name:1.png This is the ...

The usage of a shared variable is restricted in NextJS 15

Code Sandbox Link https://codesandbox.io/p/devbox/vqfy8t Issue Description In my project, I am attempting to initialize a class called Vault. Objective I aim to have a variable that can be accessed across two routes in nextJS. /send-email/ route.ts ...

Issue with Angular2-Meteor application: unable to establish connection with MySQL database through Meteor framework

Having trouble connecting to a MySQL database with Meteor using nodets:mysql and encountering the following error message: Unhandled rejection Error: No data can be retrieved from your database, please verify your permissions Here's the snippet of c ...

Is it possible to invoke an Angular2 pipe within another pipe?

When I receive data from the server, it includes an object with columns and rows. I want to loop through the columns and rows to create an HTML table, formatting the cells based on the column type using a "format" pipe. For example: Server Response: { ...

In React TypeScript, the property types of 'type' are not compatible with each other

I have a unique custom button code block here: export enum ButtonTypes { 'button', 'submit', 'reset', undefined, } type CustomButtonProps = { type: ButtonTypes; }; const CustomButton: React.FC<CustomButtonProp ...

React Native component that enables users to both input their own text and select options from a dropdown menu as they type

Looking to develop a component that combines Text Input and FlatList to capture user input from both manual entry and a dropdown list. Has anyone successfully created a similar setup? I'm facing challenges in making it happen. Here's the scenari ...

Angular DOM not reflecting updates

Having trouble with the view not detecting changes in value on a component. I've attempted to use ChangeDetectorRef without success. After trying various solutions and spending an excessive amount of time on something that should work smoothly, it see ...

Received an error while using Mongoose 6 $group with Typescript stating that the property '_id' is not compatible with the index signature

Recently, I've been transitioning from JavaScript to TypeScript and also upgrading from mongoose 5.8 to version 6.1. The code snippet below used to work perfectly before: let getActionsTakenByApp = (store_url: string) => { return AppAction.aggr ...

Ensure that the Observable is properly declared for the item list

.html // based on the error message, the issue seems to be in the HTML code <ion-card *ngFor="let invitedEvent of invitedEvents"> <ion-card-content> <img [src]="eventPhotoUrl$[invitedEvent.id] | async"> </ion ...

Angular5 Reactive Forms: Nested Form Arrays

I'm currently facing a challenge with integrating a FormArray within another FormArray. I've been struggling to find a solution for this issue. Here is the relevant part of my TypeScript file: createForm() { this.myForm = this.formBuilder.g ...

What categories do input events fall into within Vue?

What Typescript types should be used for input events in Vue to avoid missing target value, key, or files properties when using Event? For example: <input @input="(e: MISSING_TYPE) => {}" /> <input @keypress="(e: MISSING_TYPE) = ...