Is there a way to assign DTO to an entity within typescript?

For my current project, I am utilizing Vue with TypeScript and Axios to retrieve objects from the backend. Here is an example of the object type I am working with:

class Annoucement {
    id!: string;
    description?: string;
    deal?: Deal;
    realty?: Realty;
    user?: User; 
}

and the corresponding response structure:

{
  "id": "guid",
  "description": "string",
  "deal": {
     //...
  },
  "realty": {
     //...
  },
  "user": {
     //...
  }
}

The challenge arises from the fact that the properties of deal and reality may vary, making it difficult to straightforwardly map them as follows:

let annoucement = new Annoucement();
annoucement.realty.floor = dto.realty.floor;
//...

UPDATE: Here are the class definitions:

    class Deal {
        private _id!: string;
    
        private _dealInfo!: Sell | Rent; 
    
        public get id(): string {
            return this._id;
        }
    
        public set id(value: string) {
            this._id = value;
        }
    
        // more properties and methods...
    }

    // More class definitions for Sell, Rent, SellConditions, RentConditions, Realty, Office, CommercialBuilding, Building, etc.

Here is a class diagram illustrating the inheritance hierarchy

Given the variability in realty types when fetching announcements from the database, deciding on the best approach to map the response to an entity is challenging. Here are two possible solutions to address this issue:

  1. Inspect response properties with an if statement and define the type accordingly
  2. Retrieve responses in separate functions where the response structure is known beforehand

While searching for a solution online, I found that most discussions revolve around mapping entities to DTOs, rather than dealing with this specific mapping dilemma.

Answer №1

To enhance the response handling, I suggest including a realty type (perhaps as an enum) in the response object. By utilizing a switch statement, you can easily map different realty types to corresponding functions.

switch(response.type) { 
   case realty1: { 
      MapRealty1(r); 
      break; 
   } 
   case realty2: { 
      MapRealty2(); 
      break; 
   } 
   default: { 
      throw new Error('Unsupported realty type'); 
      break; 
   } 
} 

Your code needs to be informed of the realty type in order to handle it effectively. This approach ensures that the frontend and backend are in sync regarding the realty types being processed.

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

Splitting a string in Typescript based on regex group that identifies digits from the end

Looking to separate a string in a specific format - text = "a bunch of words 22 minutes ago some additional text". Only interested in the portion before the digits, like "a bunch of words". The string may contain 'minute', & ...

Is Typescript the Ultimate Replacement for propTypes in React Development?

After diving into Typescript for the first time and exploring related articles, it appears that when using Typescript with React, propTypes definitions may no longer be necessary. However, upon examining some of the most popular React Component Libraries: ...

Running tests on functions that are asynchronous is ineffective

Recently, I made the switch from Java to TypeScript and encountered a challenging problem that has been occupying my time for hours. Here is the schema that I am working with: const userSchema = new Schema({ username : { type: String, required: true }, pa ...

What is the best way to retrieve a specific property from an array of objects in Angular 6 using typescript?

I am currently working on a budgeting application that incorporates an array of expenses with a price property. Each expense is defined within an Expense model in Typescript. While I can easily access the price property using ngFor loop in HTML, I'm c ...

Retrieve data from an HTML form within an Angular 2 ag-grid component

I'm facing a challenge with incorporating form values from a modal into an ag-grid array in my HTML file. I'm unsure of the process to achieve this. Below is an excerpt from my file.html: <template #addTrainContent let-c="close" let-d="dismi ...

How does a brand new installation of VSCode believe it comes pre-equipped with TypeScript capabilities?

Operating on Windows 10 Enterprise, After investing several hours and experimenting on various VMs, Interesting Observation #1 Upon opening a .ts file in vscode, it appears to be recognized as TypeScript 2.3.4 as per the screenshot provided below: http ...

Implementing pagination within an Angular 11 Mat-table with grouping feature

Encountering an interesting issue with MatTable pagination and grouping simultaneously. I have two components each with a Mat-table featuring Pagination+Grouping. ComponentOne functions smoothly without any issues. When choosing to display 5 elements pe ...

Jest unit tests in Angular using Typescript are not detecting failures when it comes to console errors or unrecognized elements

In my Angular Typescript project, I am facing an issue with my Jest unit test. The test does not fail even if a component (e.g., mat-paginator without importing MatPaginatorModule in configureTestingModule) or template bindings (e.g., [mask] directive from ...

React's useState function causes the entire application to crash

Currently, I am working on setting up a basic menu using ASP.net core 2.1, Typescript 3.2.1, material-ui 3.8.3, and React 16.7.0. However, upon running the application, it crashes at the line containing useState showing the error message as TypeError: reac ...

Incorporate Font Awesome icons throughout your Angular8 application for added visual appeal

I'm currently working on a large Angular application that utilizes lazy loading modules. Throughout various components in different modules, I make use of icons from Font Awesome individually. Here is an example: In component.ts: import { faChevronD ...

Is there a way to determine the specific child property types of a custom Generic type extension?

I am looking to create a function that can retrieve a property from an extended generic type. Is this something achievable? Here is my attempt: interface Animal { readonly weight: {total: number} } interface Dog extends Animal { readonly weight: ...

Experiencing Typescript errors solely when running on GitHub Actions

I've been working on a React+Vite project with the Dockerfile below. Everything runs smoothly when I execute it locally, but I encounter errors like Cannot find module '@/components/ui/Button' or its corresponding type declarations and error ...

How can I eliminate the white bar elements from my dropdown menu? Also, seeking guidance on replacing an empty <div> tag in a boolean query

Can anyone help me understand the strange white border around my dropdown menu and guide me on how to remove it? I am currently using DropdownButton from react bootstrap. I have attempted to adjust the CSS with no success. Here is the code I tried: .Navig ...

Create a new visual masterpiece using Canvas by repurposing an

I am currently working on the following code snippet; export default async function draw(elRef : RefObject<HTMLCanvasElement>, tileData : TileProps) { const canvas = elRef.current!; const ctx = canvas.getContext('2d')!; ctx.clearRect( ...

Setting up the TypeScript compiler locally in the package.json file

UPDATE #1: It appears that I have managed to come up with a functional configuration, but I am open to any suggestions for improvement. Feel free to check out the answer here: THE ORIGINAL INQUIRY: I am in the process of setting up my environment so that ...

Set up an event listener for when geolocation permission is approved

My Setup: I've written some basic code snippet below: const onSuccess = () => { console.log('success'); } const onError = () => { console.log('error'); } navigator.geolocation.getCurrentPosition(onSuccess, onError) ...

What could be causing my D3.js stacked bar chart to show inaccurate results?

I'm encountering some challenges while creating a stacked bar chart in d3.js. The current appearance of my chart is depicted here (developed with D3.js): https://i.sstatic.net/G6UA6.png However, I aim to achieve a design similar to this one (crafted ...

Is it true that SPFx doesn't support JQuery?

Currently, I am in the process of developing a new SharePoint Web Part using SPFx generated by Yeoman. The scaffolding template is working well and I have encountered no issues adding NPMs for JQuery and JQueryUI. As I run GULP SERVE, everything seems to b ...

Angular Reactive Forms - Adding Values Dynamically

I have encountered an issue while working with a reactive form. I am able to append text or files from the form in order to make an http post request successfully. However, I am unsure about how to properly append values like dates, booleans, or arrays. a ...

(NG2-CHARTS) Unable to connect to the Chart Type as it is not recognized as a valid property for binding

I encountered an issue with my Chart Component where I am seeing the error message below. I have successfully imported ChartsModule into my app.module.ts file, but I am unsure why this error is occurring? Can't bind to 'ChartType' since ...