Reputation: 25963
What are the advantages of creating an interface for a angular service vs exporting the service class and using that for type information instead?
Example:
class Dashboard {
constructor(ui: IUiService){}
}
vs
class Dashboard {
constructor(ui: UiService){}
}
Is there a performance benefit? What happens if I just use the service class for type information?
It seems to be additional work with no benefit unless you have different implementations of a service that can be used but have a common base. Or when you want to mock services in unit tests instead of using them directly.
Edit: I'm interested to know what the typescript compiler will do for imports that are just used for type info. Will it invoke a constructor or add to the require statement (ES6)? Would it new up an instance of the class?
Upvotes: 1
Views: 688
Reputation: 7294
This is not a TypeScript question, this is a "What are interfaces good for" (In short) The answer is: A client should not "know" what is the real implementation of a requested service. Your UiService today is enough for your needs, but one day you might have another implementation for it, or even you would like to mock it in your tests.
Another case would be, that UiService was extended by ProUiService all over your system, you would have to go all over your system and change the type of your injects while it is not really needed.
As said before: A client should not know what is the real implementation of a requested service.
Edit (Answering the edit):
The TypeScript compiler will does not "know" where to pick these types Class/Interface you will have to use tsconfig.json or a reference (comment) in your code to let TypeScript understand where this declaration is defined. It does not matter if it's a type of a class.
It is important to understand that when you import (ES6 style) a class and never really use it (Only use it as a type definition) it will get removed by the compiler, because types does not really exist in JavaScript. BUT, if you use it. For example:
var ui = new UiService(); // This will generate a javascript code
The compiler will not remove the import statement.
Upvotes: 6
Reputation: 106650
...unless you have different implementations of a service that can be used but have a common base. Or when you want to mock services in unit tests instead of using them directly.
That's exactly why. There is no performance benefit to using interfaces as interfaces do not show up in the transpiled JavaScript.
You can use the service class for type information if you'd like and that's what's done in the angular Step by Step Guide—see Create a class for the array property and inject into component.
Upvotes: 4