2

I've been using classes for data models in my Angular applications for a while. But some time ago I saw that some developers use interfaces for that purpose. I decided to check the Angular Style Guide but didn't find any information about this. I googled a bit and found that Style Guide suggests use class instead of interface, but the link inside the question does not work (the anchor, to be precise). Then I found this comment that suggests use interfaces over classes.

I'm confused and want to know what should I use for data models?

P.S. I know the difference between classes and interfaces, especially in TypeScript. I just wanna know the best practices that Angular provides. Perhaps you could give me a link to Angular Style Guide section that will clarify everything.

Boris
  • 4,944
  • 7
  • 36
  • 69

2 Answers2

0

For most cases, interfaces are more than enough in my opinion. For a more lengthy discussion of the topic, the github issue link you provided yourself is a good source, but overall it's a matter of preference, where no option is more correct than the other.

Henrique Erzinger
  • 1,077
  • 8
  • 17
-3

The best practice is to use classes and define properties in the classes constructor public parameters, so that you can discover your models. Here's a simple example:

class Book {
  constructor(
    public name = "Default book name",
    public author = "Default author name";
  ) { }
}

PS: You absolutely need to define a default value if you need to get all the attributes later. Here's a use case where I needed to know the interfaces properties: Get class (interface) properties in Angular 5 / TypeScript without assigning a default value

Mehdi Benmoha
  • 3,694
  • 3
  • 23
  • 43
  • Agree! Could you please provide some official link that confirms this best practice? – Boris Oct 16 '19 at 20:19
  • I see how that would be your preferred method, but what exactly makes it a best practice? – Henrique Erzinger Oct 16 '19 at 20:20
  • I still remember when It was in the Angular style guide, but now, they removed a lot of things from it so, I don't know if it's still an Angular best practice. But, here's a case where I needed that style of model classes: https://stackoverflow.com/questions/49174696/get-class-interface-properties-in-angular-5-typescript-without-assigning-a-d – Mehdi Benmoha Oct 16 '19 at 20:27
  • 1
    I'm pretty sure the exact opposite was part of the official style guide once. The fact they removed it one way or another makes me think it is validation of my idea that it's a matter of personal preference. – Henrique Erzinger Oct 16 '19 at 20:29