When to use Interface and Model in TypeScript / Angular2

后端 未结 4 794
不知归路
不知归路 2020-11-29 15:19

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

相关标签:
4条回答
  • 2020-11-29 15:30

    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:

    • How do I cast a JSON object to a typescript class
    • How to get Date object from json Response in typescript

    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);
          });
        });
    
    0 讨论(0)
  • 2020-11-29 15:31

    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.

    0 讨论(0)
  • 2020-11-29 15:34

    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.

    0 讨论(0)
  • 2020-11-29 15:35

    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.

    0 讨论(0)
提交回复
热议问题