接口就是在面向对象编程中的一种规范的定义,定义行为和动作,起到一种限制和规范代码的作用,如果有学过c#和java这类面向对象的语言的话就非常容易懂了
1、属性接口
//对类属性的约束
interface Person{
name:string;
age:number
}
2、对函数的约束
interface Memo{ //对函数的约束
(value:number,name:string):void
}
3、对数组的约束
interface Arr{ //定义数组
[index:number]:string //index:索引值,
}
let arr:Arr=['ddd'] //value为string
4、对象的约束
interface Obj{ //定义对象
[index:string]:string //index:索引值,
}
let ob:Obj={name:'123'} //value为string
5、接口的实现
interface Anmails{
name:string;
eat(name:string):void
}
class Dog implements Anmails{ //implements关键字 为‘实现’ 相当于class Dog 实现Anmails 接口
name:string;
constructor(name:string){
this.name=name
}
eat(name:string){
console.log(this.name)
}
}
6、接口的继承
//接口的继承
interface Anmails{
eat(food:string):string
}
interface Cat extends Anmails{
runing():void
}
class buleCat implements Cat{
name:string
constructor(name:string){
this.name=name
}
eat(food:string){
return this.name+'吃'+food
}
runing(){
console.log( this.name+'在跑');
}
}
var xiaoke = new buleCat('小可');
xiaoke.eat('猫粮')
xiaoke.runing()