ts裡面的介面:
介面是一系列抽象方法的宣告,是一些方法特徵的集合,這些方法都應該是抽象的,需要由具體的類去實現。
例項:
interface IPerson { firstName:string, lastName:string, sayHi: ()=>string } var customer:IPerson = { firstName:"Tom", lastName:"Hanks", sayHi: ():string =>{return "Hi there"} } console.log("Customer 物件 ") console.log(customer.firstName) console.log(customer.lastName) console.log(customer.sayHi())
var employee:IPerson = { firstName:"Jim", lastName:"Blakes", sayHi: ():string =>{return "Hello!!!"} } console.log("Employee 物件 ") console.log(employee.firstName) console.log(employee.lastName)
聯合型別介面:
interface RunOptions { program:string; commandline:string[]|string|(()=>string); } // commandline 是字串 var options:RunOptions = {program:"test1",commandline:"Hello"}; console.log(options.commandline) // commandline 是字串陣列 options = {program:"test1",commandline:["Hello","World"]}; console.log(options.commandline[0]); console.log(options.commandline[1]); // commandline 是一個函式表示式 options = {program:"test1",commandline:()=>{return "**Hello World**";}}; var fn:any = options.commandline; console.log(fn());
陣列型別的介面:
interface namelist { [index:number]:string } // 型別一致,正確 var list2:namelist = ["Google","Runoob","Taobao"] // 錯誤元素 1 不是 string 型別 // var list2:namelist = ["Runoob",1,"Taobao"]
介面繼承:可以透過繼承其他介面來擴充自己。
interface Person { age:number } interface Musician extends Person { instrument:string } var drummer = <Musician>{}; drummer.age = 27 drummer.instrument = "Drums" console.log("年齡: "+drummer.age) console.log("喜歡的樂器: "+drummer.instrument)
多繼承:
interface IParent1 { v1:number } interface IParent2 { v2:number } interface Child extends IParent1, IParent2 { } var Iobj:Child = { v1:12, v2:23} console.log("value 1: "+Iobj.v1+" value 2: "+Iobj.v2)
打完收工!