Search code examples
angulartypescriptclassinterface

When to use Interface and Model in TypeScript / Angular


I recently watched a Tutorial on Angular 2 with TypeScript, but unsure when to use an Interface and when to use a Model for data structures.

Example of interface:

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

Example of Model:

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

I want to load a JSON data from a URL and bind to the Interface/Model. Sometime I want a single data object, other time I want to hold an array of the object.

Which one should I use and why?


Solution

  • 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);
          });
        });