Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why styleguide suggest use class instead of interface? #846

Open
copiali opened this issue Oct 10, 2017 · 3 comments
Open

Why styleguide suggest use class instead of interface? #846

copiali opened this issue Oct 10, 2017 · 3 comments

Comments

@copiali
Copy link

copiali commented Oct 10, 2017

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
Copy link

bampakoa commented Oct 11, 2017

@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
Copy link

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
Copy link

jpreese commented Dec 2, 2017

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants