DTO - Interface x Class

0

I have used Interface to create Data Transfer Objects (DTO), "dumb" objects that only serve to standardize the communication of objects between the front and the back. My question is: Really using Interface is best practice? Or would it be better to use classes? What do you think about it?

Ex:

interface UserDTO {

    name?: string;
    mailAddress?: string;
    phone?: string;
}

 params: UserDTO;

_save(user): void {

   this.params = {};

   this.params.name = user.name;
   this.params.mailAddress = user.mailAddress;
   this.params.phone = user.phone;

   [...]
}

I just have to set the properties to nullable to be able to initialize the interface with empty object, so that null reference exception does not occur. That's exactly what's bothering me. If I use class, I would solve this by instantiating a User object. I hope I have been clear.

    
asked by anonymous 21.04.2017 / 18:30

1 answer

0

The interface can be a way of typing a JSON structure. The advantage of using direct interface is to treat the object as a pure JSON. Since this allows you to create the direct object in this notation.

EX:

this.params = {
     name: "Nome",
     mailAddress: "[email protected]",
     phone: "55555555"
}

As you want to create a JSON with fields that may not exist, it would be more practical to actually use Class. But you would have to convert this to JSON before saving:

class UserDTO {

    name: string;
    mailAddress: string;
    phone: string;
}

params: {} = {};

_save(user: UserDTO): void {

    this.params = JSON.stringify(user);

    [...]
}
    
08.09.2017 / 22:42