【问题标题】:Implement Ionic 2 Model by Using Interfaces and Class使用接口和类实现 Ionic 2 模型
【发布时间】:2018-08-09 23:07:31
【问题描述】:

在 Ionic 2 中声明模型时,我看到有两个这样做。通过接口或类

接口代码:

export interface BlogPost {
  postId: number,
  title: string
}

类代码:

export class BlogPost{
  public object: {};
  constructor(
    public postId: number,
    public title: string
  ) {
    this.object = {
      postId: this.postId,
      title: this.title,
    };
  }
}

我不确定它们之间有什么区别,有什么方法可以让我们在 Ionic 2 中提前声明一个预定义的值。就像

export interface BlogPost {
  postId: number,
  title: string,
  comments: string = 'Test'
}

谢谢,

【问题讨论】:

    标签: typescript ionic-framework ionic2 ionic3


    【解决方案1】:

    你是对的 - 该接口用于类型检查。看看这个documentation。如果要声明某种类型的变量,请创建一个类,然后将一个对象声明为该类类型。

    例如

    // This interface declares that an object must have a 'name' attribute.
    interface IPerson {
        name: string;
    }
    
    // This class, which implements IPerson, must have a 'name' attribute.
    class Person implements IPerson {
        name: string;
        age: number;
        address: string;
    }
    
    // We can assume that the argument has a 'name' attribute,
    // because the parameter is of type IPerson.
    showName(p: IPerson) {
        console.log(p.name);
    }
    
    let someone: Person = new Person();
    this.showName(someone);
    

    【讨论】:

      【解决方案2】:

      我应该阅读这篇关于 TypeScript 中的类和接口的博客:https://toddmotto.com/classes-vs-interfaces-in-typescript

      仍然不确定如何预定义变量。可能是不可能的,因为 Model 主要是用来做类型检查的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-20
        • 1970-01-01
        • 2017-04-03
        • 1970-01-01
        相关资源
        最近更新 更多