DTO - Interface x Class

Asked

Viewed 408 times

0

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

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 end up having to define the properties as nullable to be able to initialize the interface with empty object, so that it does not occur null Reference Exception. That’s exactly what’s bothering me. If I used class I would solve it by instantiating an object User. I hope I was clear.

  • Thank you. I was doing that now.

1 answer

0

The interface can be a way to type 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"
}

Since 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);

    [...]
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.