它们具有相似的结构,但以不同的方式使用。该类允许您创建要在应用程序中使用的新对象。接口告诉编译器应该如何构造事物。您可以在下面看到您可以向标签属性添加值。您不能使用界面执行此操作。
interface Something {
label: string;
}
class Something {
label: string = 'some string value';
}
在下面的示例中,接口强制Something 类始终需要名为label 的属性,并且类型必须是string。如果您更改类型或一起删除属性。编译器会报错。
interface ISomething {
label: string;
}
class Something implements ISomething {
label: string = 'some string value';
}
在上面的示例中,我建议使用在接口名称前添加大写字母I 的约定,以消除类和接口之间的混淆。
在下一个示例中,我们将使用一个接口 (IUser) 来允许将多个类传递给 getUserDescription 函数,而不会引起编译器的抱怨。这称为多态性。我们的函数不关心它是教师、学生还是任何其他班级。它只关心传入的结构是否与接口匹配。
interface IUser {
firstName: string;
lastName: string;
type: string;
}
class Student {
firstName: string = null;
lastName: string = null;
type: string = 'student';
courses: Array<any> = [];
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
}
class Teacher implements IUser {
firstName: string = null;
lastName: string = null;
type: string = 'teacher';
classes: Array<any> = [];
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
}
const getUserDescription = (user: IUser): string => {
return `${user.firstName} ${user.lastName} is a ${user.type}`;
};
getUserDescription(new Teacher('Harry', 'Jones')); // Harry Jones is a teacher
getUserDescription(new Student('Joe', 'Cool')); // Joe Cool is a student
如果您注意到上面的 Teacher 实现了 IUser 但 Student 没有。通常你会以同样的方式完成,但我想表明你可以在班级级别强制执行结构。
查看我的文章 http://www.codebelt.com/typescript/typescript-classes-object-oriented-programming/ 了解更多信息。