什么是接口
接口是一种"规范" 。看清了啊,这里和java、php中的接口是有点区别 的啊。这里是"规范"。表示某一些参数需要符合某一种"规范"。
接口的声明:
Interface 接口名称 {
属性名:属性类型
}
场景:
记不记得我们以前考试的时候,都有一个"准考证号"。没有准考证号的人是不能进入考场的,监考老师在我们入场的时候,需要检查我们的准考证号,没有准考证号的人是不能进入考场的。
TypeScript
// 考生的接口,考生必须有stuId的属性
interface IStu {
stuId: string;
}
class Teacher {
public checkStuId(stu: IStu): void {
console.log("我的准考证是:", stu.stuId);
}
}
class BoyStu {
public name: string = "男生";
public stuId: string = "123"; // 准考证号
}
class GirlStu {
public name: string = "女生";
public stuId: string = "456"; // 准考证号
}
class Other {
public name: string = "其他人";
}
let boy: BoyStu = new BoyStu();
let girl: GirlStu = new GirlStu();
let other: Other = new Other();
let teacher: Teacher = new Teacher();
teacher.checkStuId(boy);
teacher.checkStuId(girl);
// teacher.checkStuId(other);

查看以上,可以看到other不能传递到"老师"的checkStuId的参数里,因为这个other没有stuId的属性。而boy和girl都有stuId属性,所以,他们可以传递到"老师"的checkStuId的方法中。