I recently watched a Tutorial on Angular 2 with TypeScript, but unsure when to use an Interface and when to use a Model to hold data structures.
Example of interface
Interfaces are only at compile time. This allows only you to check that the expected data received follows a particular structure. For this you can cast your content to this interface:
this.http.get('...')
.map(res => <Product[]>res.json());
See these questions:
You can do something similar with class but the main differences with class are that they are present at runtime (constructor function) and you can define methods in them with processing. But, in this case, you need to instantiate objects to be able to use them:
this.http.get('...')
.map(res => {
var data = res.json();
return data.map(d => {
return new Product(d.productNumber,
d.productName, d.productDescription);
});
});
The Interface describes either a contract for a class or a new type. It is a pure Typescript element, so it doesn't affect Javascript.
A model, and namely a class, is an actual JS function which is being used to generate new objects.
I want to load JSON data from a URL and bind to the Interface/Model.
Go for a model, otherwise it will still be JSON in your Javascript.
Use Class instead of Interface that is what I discovered after all my research.
Why? A class alone is less code than a class-plus-interface. (anyway you may require a Class for data model)
Why? A class can act as an interface (use implements instead of extends).
Why? An interface-class can be a provider lookup token in Angular dependency injection.
from Angular Style Guide
Basically a Class can do all, what an Interface will do. So may never need to use an Interface.
As @ThierryTemplier said for receiving data from server and also transmitting model between components (to keep intellisense list and make design time error), it's fine to use interface but I think for sending data to server (DTOs) it's better to use class to take advantages of auto mapping DTO from model.