首页 文章

何时在TypeScript / Angular2中使用Interface和Model

提问于
浏览
146

我最近使用TypeScript观看了Angular 2的教程,但不确定何时使用接口以及何时使用模型来保存数据结构 .

界面示例:

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

型号示例:

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

我想从URL加载JSON数据并绑定到接口/模型 . 有时我想要一个数据对象,其他时候我想要持有对象的数组 .

我应该使用哪一个?为什么?

4 回答

  • 103

    接口仅在编译时 . 这样只允许您检查收到的预期数据是否遵循特定结构 . 为此,您可以将内容转换为此界面:

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

    看到这些问题:

    您可以使用类来执行类似的操作,但与类的主要区别在于它们存在于运行时(构造函数),您可以使用处理来定义它们中的方法 . 但是,在这种情况下,您需要实例化对象才能使用它们:

    this.http.get('...')
        .map(res => {
          var data = res.json();
          return data.map(d => {
            return new Product(d.productNumber,
              d.productName, d.productDescription);
          });
        });
    
  • 35

    Interface 描述了类的 Contract 或新类型 . 它是一个纯粹的Typescript元素,因此它不会影响Javascript .

    模型,即类,是用于生成新对象的实际JS函数 .

    我想从URL加载JSON数据并绑定到接口/模型 .

    去寻找模型,否则它仍然是Javascript中的JSON .

  • -8

    正如@ThierryTemplier所说,从服务器接收数据并在组件之间传输模型(保持智能感知列表并使设计时间错误),使用接口是好的,但我认为将数据发送到服务器(DTO)最好使用类来接受从模型中自动映射DTO的优点 .

  • 2

    Use Class instead of Interface 这是我在所有研究之后发现的 .

    为什么?单独一个类的代码少于类加接口 . (无论如何,你可能需要一个数据模型类)

    为什么?类可以充当接口(使用implements而不是extends) .

    为什么?接口类可以是Angular依赖注入中的提供者查找标记 .

    from Angular Style Guide

    基本上,一个类可以做所有,接口将做什么 . So may never need to use an Interface .

相关问题