一、接口:一系列抽象方法的聲明,是一些方法特征的集合,這些方法都應(yīng)該是抽象的,需要由具體的類去實(shí)現(xiàn),然后第三方就可以通過(guò)這組抽象方法調(diào)用,讓具體的類執(zhí)行具體的方法。
1)、語(yǔ)法:
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)、聯(lián)合類型和接口
例如:
interface ff{
? ? porg : string,
? ? comm : string[] | string | (()=>string)
}
// 字符串?dāng)?shù)組
let aa : ff = {
? ? porg : "吳剛",
? ? comm : ["岳秀清",'吳與卿','吳剛'],
}
console.log(aa.comm[0]);? ? //岳秀清
console.log(aa.comm[1]);? ? ? ? //吳與卿
console.log(aa.comm[2]);? ? ? ? //吳剛
//函數(shù)表達(dá)式
let nn : ff = {
? ? porg : '吳剛',
? ? comm : ()=>{
? ? ? ? return "岳秀清"
? ? }
}
let ll : any = nn.comm
console.log(ll());? ? ? //岳秀清
3)、接口和數(shù)組:接口中我們可以將數(shù)組的索引值和元素設(shè)置為不同類型,索引值可以是數(shù)字或字符串。
例如:
interface ff {
? ? [index:number]:string
}
let list : ff = ['吳剛','岳秀清'];
console.log(list)
4)、接口繼承:接口可以通過(guò)其他接口來(lái)擴(kuò)展自己;Typescript 允許接口繼承多個(gè)接口;繼承使用關(guān)鍵字 extends。
語(yǔ)法:
單接口繼承語(yǔ)法
Child_interface_name extends super_interface_name
多接口繼承語(yǔ)法
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