johnpapa / angular-styleguide

Angular Style Guide: A starting point for Angular development teams to provide consistency through good practices.
http://johnpapa.net
MIT License
23.91k stars 4.16k forks source link

Why styleguide suggest use class instead of interface? #846

Open copiali opened 6 years ago

copiali commented 6 years ago

In style guid, it says consider use class instead of interface https://angular.io/guide/styleguide#interfaces

Also in the example file hero.model.ts it's using class: export class Hero { id: number; name: string; }

I think in this case better use interface instead of class when you it's just shape of the model? As I think typescript best practice is that in this case. Unlike classes, interfaces are completely removed during compilation and so they will not add any unnecessary bloat to our final JavaScript code.

Any reason to use class instead of interface in this case?? Or it's better to use interface in this case?

bampakoa commented 6 years ago

@copiali Classes have proven very useful to me in the case of unit testing where I have to create mock objects using their constructor:

export class Hero {
   constructor(public id: number, public name: string) {}
}

const mockHero = new Hero(1, 'My hero');
renestalder commented 6 years ago

I also found that interfaces are better. Especially when you start to work with state managers, you get some problems when trying to save class objects to the state.

jpreese commented 6 years ago

I'm glad this issue so recent, as I have the same question. In @bampakoa's case, I don't believe you'd need to instantiate the Hero class. If you had an Interface, you could simply do

const stubHero: Hero = {
  id: 1,
  name: 'My hero'
}

I see the value in classes when dealing with methods and actual implementations. Though I think I'd prefer interfaces when modeling data as we're talking about here. Are we missing something as to why the guide suggests otherwise?