一、接口:一系列抽象方法的声明,是一些方法特征的集合,这些方法都应该是抽象的,需要由具体的类去实现,然后第三方就可以通过这组抽象方法调用,让具体的类执行具体的方法。
1)、语法:
interface interface_name {
}
例如:
interface IPerson{
firstname : string,
lastname : string,
say : ()=>string
}
let cus :IPerson={
firstname : 'King',
lastname : 'wroker',
say : ():string=>{return 'beijing hello'}
}
console.log(cus.firstname) //King
console.log(cus.lastname) //wroker
console.log(cus.say()) //beijing hello
let str : IPerson={
firstname : '韩信',
lastname : '刘邦',
say : () : string => {
return '萧何月下追韩信'
}
}
console.log(str.firstname); //韩信
console.log(str.lastname); //刘邦
console.log(str.say()); //萧何月下追韩信
2)、联合类型和接口
例如:
interface ff{
porg : string,
comm : string[] | string | (()=>string)
}
// 字符串数组
let aa : ff = {
porg : "吴刚",
comm : ["岳秀清",'吴与卿','吴刚'],
}
console.log(aa.comm[0]); //岳秀清
console.log(aa.comm[1]); //吴与卿
console.log(aa.comm[2]); //吴刚
//函数表达式
let nn : ff = {
porg : '吴刚',
comm : ()=>{
return "岳秀清"
}
}
let ll : any = nn.comm
console.log(ll()); //岳秀清
3)、接口和数组:接口中我们可以将数组的索引值和元素设置为不同类型,索引值可以是数字或字符串。
例如:
interface ff {
[index:number]:string
}
let list : ff = ['吴刚','岳秀清'];
console.log(list)
4)、接口继承:接口可以通过其他接口来扩展自己;Typescript 允许接口继承多个接口;继承使用关键字 extends。
语法:
单接口继承语法
Child_interface_name extends super_interface_name
多接口继承语法
Child_interface_name extends super_interface1_name, super_interface2_name,…,super_interfaceN_name
例如:
单接口继承:
interface ff{
age : number
}
interface mm extends ff{
instrument:string
}
let aa = <mm>{};
aa.age = 15
aa.instrument="吴刚"
console.log('年龄:'+aa.age); //年龄:15
console.log("姓名:"+aa.instrument); //姓名:吴刚
多接口继承:
interface ff{
v : number
}
interface nn{
v1 : number
}
interface child extends ff,nn{ }
let obj = {v : 23,v1 : 12};
console.log(obj.v ,obj.v1) //23 12