When to use the interface and model in TypeScript / Angular2

I recently looked at an Angular 2 tutorial with TypeScript, but I donโ€™t know when to use the interface and when to use the model to store data structures.

Interface example:

export interface IProduct { ProductNumber: number; ProductName: string; ProductDescription: string; } 

Model Example:

 export class Product { constructor( public ProductNumber: number, public ProductName: string, public ProductDescription: string ){} } 

I want to load JSON data from a url and bind to an interface / model. Sometimes I need one data object, at other times I want to hold an array of the object.

Which should I use and why?

+170
angular typescript
Jun 06 '16 at 8:30
source share
2 answers

Interfaces are found only at compile time. This allows you only to verify that the expected received data matches a specific structure. To do this, you can transfer your content to this interface:

 this.http.get('...') .map(res => <Product[]>res.json()); 

See the following questions:

  • How to create a JSON object for typescript class
  • How to get Date object from json Response in typescript

You can do something similar with the class, but the main differences of the 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 the objects in order 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); }); }); 
+120
Jun 06 '16 at 8:39
source share

An interface describes either a contract for a class or a new type. This is a pure Typescript element, so it does not affect Javascript.

A model, namely a class, is a real JS function that is used to generate new objects.

I want to load JSON data from a url and bind to an interface / model.

Go for the model, otherwise it will still be JSON in your Javascript.

+38
Jun 06 '16 at 8:42 on
source share



All Articles