I_LIKE_FOO I_LIKE_FOO - 1 year ago 102
TypeScript Question

When to use Interface and Model in TypeScript / Angular2

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:

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

Example of Model:

export class Product {
public ProductNumber: number,
public ProductName: string,
public ProductDescription: string

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

Which one should I use and why?

Answer Source

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:

    .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:

    .map(res => {
      var data = res.json();
      return data.map(d => {
        return new Product(d.productNumber,
          d.productName, d.productDescription);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download