typescript 接口
接口:在面向对象的编译中,接口是一种规范的定义,它定义了行为和动作的规范,定义标准
interface 关键字定义接口
属性类型接口 对属性进行定义 (批量约束)
interface People{ name:string; age:number; } function getPeople(p:People):void{ console.log(`${p.name}的年龄是${p.age}`) } let son = { name:'张三', age:20 } getPeople(son);
可选属性
interface People{ name:string; age:number; sex?:string; //属性后加 ?为可选属性,可传可不传 }
函数类型接口 对方法传入的参数以及返回值进行约束 (批量约束)
interface sum{ (x:number,y:number):number; } let getSum:sum = function(x:number,y:number):number{ return x+y };
可索引接口 对数组、 对象进行约束 (不常用)
interface UserArr{ [index:number]:string; // 或者any } let arr:UserArr = ['Tom','Jerry'] interface UserObj{ [index:string]:string } let UserObj:UserObj = { name0:'Tom', name1:'Jerry' }
类类型接口 对类的约束 (和抽象类有点相似)
interface People{ name:string; info(str:string):void } class Child implements People{ name:string; constructor(name:string){ this.name = name; }
info(name:string){
console.log('我叫'+this.name)
}
}
接口扩展 接口可以继承接口
interface Animal{ eat():void } interface Person extends Animal{ work():void; } class Student implements Person { name:string; constructor(name:string) { this.name = name; } eat(){ console.log(this.name + '吃肉肉') } work(){ console.log(this.name + '敲代码'); } }