How can i map DTO to entity in typescript?

  Kiến thức lập trình

In my project, I use Vue + TypeScript and Axios to get objects from the backend. So, I have an object type like this:

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

and a response like this:

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

The main problem is that deal and reality can have different properties, thats why I cant just use something like this

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

So I have just two solution of this problem:

  1. Check responses properties with if` and define type
  2. Get responses in different functions, where i will know the response structure.

I have tried to find a solution in Google. But in most cases, people ask how to map an entity to a DTO.

LEAVE A COMMENT