interface P1{
name:string
age:number
}
class xiao implements P1{
name: string;
age: number;
constructor(name:string, age:number){
this.name = name
this.age = age
}
}
意思就是要让前者满足后面的形状(字段及类型)
继承多个接口
interface P1{
name:string
age:number
}
interface P2{
name1:string
age1:number
}
class xiao implements P1,P2{
name: string;
age: number;
name1: string;
age1: number;
constructor(name:string, age:number){
this.name = name
this.age = age
this.name1 = name
this.age1 = age
}
}
案例:
在js中,一个class只能继承自另一个class,若其他类中的方法与属性也想继承,则很麻烦。而在ts中可以使用implements来实现一些类共有方法属性的提取。
class Car{
switchRadio(trigger:boolean){
}
}
class cellphone{
switchRadio(trigger:boolean){
}
}
上述两个类都有一个共同的方法,我们可以使用interface接口把他提取出来,implements实现它。此时car和cellphone两个类中都需要有switchRadio方法,不然会报错。
interface Radio{
switchRadio(trigger:boolean):void //注意写法,void表示函数没有返回值
}
class Car implements Radio{
switchRadio(trigger:boolean){
}
}
class cellphone implements Radio{
switchRadio(trigger:boolean){
}
}
新加一个Battery interface,使cellphone类接入而car类不接入。
interface Battery{
checkBatteryStatus():void;
}
interface Radio{
switchRadio(trigger:boolean):void; //注意写法,void表示函数没有返回值
}
class Car implements Radio{
switchRadio(trigger:boolean){
}
}
class cellphone implements Radio,Battery{ //逗号连接
switchRadio(trigger:boolean){
}
checkBatteryStatus(){ //内部方法加上checkBatteryStatus,注意:不能少!!!!!
}
}
interface还可以继承,直接用extends即可
interface Battery{
checkBatteryStatus():void;
}
interface Radio{
switchRadio(trigger:boolean):void; //注意写法,void表示函数没有返回值
}
interface BatterywithRadio extends Radio{
checkBatteryStatus():void;
}
class Car implements Radio{
switchRadio(trigger:boolean){
}
}
class cellphone implements BatterywithRadio{ //逗号连接
switchRadio(trigger:boolean){
}
checkBatteryStatus(){
}
}