Simplify deeply nested JSON structures with TypeScript generics

After receiving the JSON data shown below, I have a specific model in mind for deserialization:

{"results":
  {"data": {
    "id":"93cba9bd-2969-3214-b26f-7f42d20241a4",
    "first_name":"PSU",
    "last_name":"Bot",
    "profile": {
        "data":{"about":"i am so happy",}
     }
  }
}

The desired model is as follows:

export class Person extends BaseModel {
    first_name: string;
    last_name: string;
    profile: DataType<Profile>;
}

The aim is to have the profile property without the nested data element.

To achieve this, I am looking into constructing a generic DataType. Here's my initial attempt:

export class DataType<T> {

public constructor(arg: T) {
    console.log(arg);
    return new arg.data;
  }
}

I'm wondering if this falls under generic type territory or should be treated as an object (class) similar to the example above. Any insights on this would be appreciated.

Answer №1

When dealing with nested logic, there are a couple of ways to approach it.

export class DataType<T> {
  public constructor(public data: T) {}
}

Another option is to delegate the task like this:

export class DataType<T> {
  public data: T;

  public constructor(obj: {"data":T}) {
    this.data = obj.data;
  }
}

Answer №2

If you are confident that the profile property or any other value replacing it will contain the data property, you can create a versatile class to represent that part of the response:

export class DataType<T extends { data: any }> {
    public data: any;

    public constructor(arg: T) {
        this.data = arg.data;
    }

    public toJSON(): any {
        return {
            data: this.data,
        };
    }
}

Remember, the toJSON method is optional but can be helpful when using JSON.stringify on this object or its parent. It allows you to customize the output as needed.

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

Best practices for organizing API Services using TypeScript and Next.js Server Actions

My product-actions/index file contains various server actions such as createProduct and getProductAssets, each of which verifies the user session before processing the request. I am looking for a way to check the session validity only once and then procee ...

Angular 2 Validation Customizer

Recently, I created a web API function that takes a username input from a text field and checks if it is already taken. The server response returns Y if the username is available and N if it's not. For validating the username, I implemented a Validat ...

Having trouble with code behaving differently than expected in Chrome's debugger

I've come across a peculiar issue in my TypeScript project (an Angular application). Here's the code snippet that's causing trouble: const idx = myclone.findIndex(x => x.id === action.id); const hasVal = idx>-1; // for some reason, Chr ...

When using TypeORM's save() method with an array of objects, the @PrimaryColumn() annotations are ignored, resulting

My current situation involves an entity called Point: @Entity() export class Point { @PrimaryGeneratedColumn('uuid') id: string; @IsUUID() @PrimaryColumn({ type: 'uuid', ...

Error encountered when asynchronously iterating over an object in TypeScript

Could someone please help me understand why I am getting an error with this code? var promise = new Promise((resolve, reject) => { resolve([1, 2, 3, 4, 5]); }); async function doSomethingAsync() { var data = await promise; data.forEach(v = ...

The proper injection of the NestJS module is essential for seamless functionality

When working with Nest, I created a new module using the command nest g module UserModule src/user-module/user.resolver.ts contains the following code: import { Query, Resolver } from '@nestjs/graphql'; import { UserService } from './user.s ...

Exploring Angular Unit Testing: A Beginner's Guide to Running a Simple Test

I'm diving into the world of angular unit testing and looking to set up my first successful test. Here's what I've come up with: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AppComponent } fro ...

What steps can I take to ensure TypeScript compiler approves of variance in calling generic handlers, such as those used in expressJS middleware?

disclaimer: I am a bit uncertain about variance in general... Here is the scenario I am facing: // index.ts import express from 'express'; import {Request, Response} from 'express'; const app = express(); app.use(handler); interface ...

What are the steps to resolve the issue of assigning void type to type ((event: MouseEvent<HTMLDivElement, MouseEvent>) => void) | undefined in a react application?

I'm trying to update the state isOpen to true or false when clicking on a div element, but I keep getting an error with the following code: function Parent() { const [isOpen, setIsOpen] = React.useState(false); return ( <Wrapper> ...

ERROR: Issue detected in the e class under the e_Host - inline template 0:0

As I was upgrading my angular2 project to RC5, a major issue surfaced. Despite reducing all the code to its minimum in order to debug the problem, I couldn't pinpoint its origin. Every request made by my app led to the following error message (as seen ...

Securing pathways in Next.js using middleware and Next-Auth

Hey there, I'm currently working on adding some route protection in NextJS using middleware for authentication with next-auth. According to the documentation, this is what my middleware.ts file should look like: export { default } from "next-auth ...

How to fix an unresolved TypeScript import?

Within my node_modules directory, there is a package that contains the following import statement: import { x } from 'node_modules/@types/openfin/_v2/main'; Unfortunately, I am receiving an error message stating "cannot find module 'node_mo ...

Is it possible to automatically correct all import statements in a TypeScript project?

After transferring some class member variables to a separate class in another file, I realized that these variables were extensively used in the project. As a result, approximately 1000 .ts files will need their imports modified to point to the new class/f ...

Converting language into class components using ngx-translate in Angular

Seeking to convert the information from a table into my typescript class. The data in the table is sourced from a JSON file within the /assets directory. Is there a method to accomplish this task? How can I categorize translation within a typescript class ...

The width of the Bootstrap tooltip changes when hovered over

Currently, I am facing a peculiar issue with my angular web-application. Within the application, there is a matrix displaying data. When I hover over the data in this matrix, some basic information about the object pops up. Strangely, every time I hover ov ...

Obtain a value that is not defined

Good day, I am encountering an issue with my data not accepting an undefined value. Below is the code snippet: interface IModalContatos { dados: IContatos; onSave(dados: IContatos): void; onClose(): void; } When passing this data to my modal, I rece ...

Methods to validate CSS attributes specified within a class using React testing library

I am struggling to validate the CSS properties defined within a class in CSS using the React Testing Library. Unfortunately, I am facing challenges in doing so. Here are the simplified code snippets: import React from "react"; import { render, ...

Angular - pipe function disrupts the flow of execution

Here is the code snippet in question: subscriber.pipe( switchMap(data => { this.getData().pipe( map(() => res), catchError(error => { return of(null); }) ...

Unable to activate the AWS IoT security audit using CDK

I'm trying to activate the AWS IoT security audit using a CDK stack, but I'm encountering some issues. Initially, I referred to this documentation for the interfaceAuditCheckConfigurationProperty and implemented the following CDK code to enable ...

Loading preferred routes in Angular 6+ Universal for faster performance

In my Angular 7 application, I have Angular Universal set up with Express and I am also utilizing Angular Routing. My goal is to have only the pre-login routes (marketing views) rendered server-side, while post-login routes are loaded using traditional cli ...