typescript-接口的基本使用(一)

什么是接口

接口是一种"规范" 。看清了啊,这里和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的方法中。

相关推荐
阿蒙Amon10 小时前
TypeScript学习-第10章:模块与命名空间
学习·ubuntu·typescript
Doro再努力10 小时前
【Linux操作系统10】Makefile深度解析:从依赖推导到有效编译
android·linux·运维·服务器·编辑器·vim
Daniel李华11 小时前
echarts使用案例
android·javascript·echarts
北原_春希11 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS11 小时前
echarts天气折线图
javascript·vue.js·echarts
尽意啊11 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜11 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive11 小时前
Vue3使用ECharts
前端·javascript·echarts
竹秋…11 小时前
echarts自定义tooltip中的内容
前端·javascript·echarts
宝贝露.11 小时前
Axure引入Echarts图无法正常显示问题
前端·javascript·echarts