1. 程式人生 > 實用技巧 >typeScript學習筆記-02

typeScript學習筆記-02

介面

// 介面:對行為的 抽象
// 1對class的約束
// 介面定義
interface Iprinter{  //定義一個印表機
   Printing(msg:string):string; //傳的參是字串 括號外冒號後邊的string表示返回的是字串
}

interface Imessage{  
    getmsg():string; 
 }

// 實現介面Iprinter    (implements特定語法)   /實現多個介面
class colorpronter implements Iprinter,Imessage{
  Printing(msg:string):string{
      
return "列印"+msg+"成功" } getmsg():string{ return "dell" } } let p1=new colorpronter() let val=p1.Printing('簡歷') console.log(val) console.log(p1.getmsg()) //1 實現介面 要實現裡面的內容 // 2定義介面的時候,只定義宣告即可,不包含具體內容 // 2對函式的約束 interface Imyfaction{ //定義介面 (a:string,b:number):boolean; } let fun1:Imyfaction; fun1
=function(a:string,b:number):boolean{ return false; } // 3對陣列的約束 interface Istuarr{ [index:number]:string; } let arr3:Istuarr; arr3=["aa","11"] console.log(arr3[0]) // 對json的約束 interface Idata{ name:string, age:number, readonly sex?:string// 只讀屬性 email?:string //可選屬性 } function showdata(n:Idata){
// n.sex=11; 會報錯應為sex設定的是隻讀的不能被修改 n.age=11 console.log(JSON.stringify(n)) } showdata({name:'lisy',age:20})