在Ionic 2中声明一个Model时,我看到有两个这样做。通过接口或类
接口代码:
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中的类和接口的博客:https://toddmotto.com/classes-vs-interfaces-in-typescript
仍然不确定如何预定义变量。也许这是不可能的,因为模型主要用于类型检查。
你是对的 - 界面用于类型检查。看看这个documentation。如果要声明某种类型的变量,请创建一个类,然后将对象声明为该类类型。
EG
// 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);