跳到主要內容

發表文章

精選

[TS筆記] type 和 interface 區分

 對於新手來說 type 與 interface 很容易混淆,兩者的用法也相當接近。 但細看又有些差異性,這邊先主要介紹兩個的用法、相異處做解釋。 「?」代表著可有可無,如果沒有則為必須值 Type 以下這段說明House的型別中,有roof、wall等屬性, desk為可有可無。 type House ={ roof: string, wall: string, desk?: number, } Interface 以下這段說明House的型別中,有roof、wall等屬性, desk為可有可無。 Interface House ={ roof: string, wall: string, desk?: number, } 先等等,如果只是單看定義無法辨別出兩者的差異。但可以很明顯看出這兩者用法是定義出function或是靜態型別。 使用相異處,這邊先舉兩個例子: 例子一: type可以直接宣告成基本型別,但同樣的例子來說interface無法宣告成基礎型別。 type House = string; //correct✅ interface House = string; //mistake ❌ 例子二: type無法繼承/可被繼承,interface可以繼承/被繼承。 //mistake example🔻 type roof = {color: string }; type House extends roof = { color: string }; //correct example🔻 interface roof { color: string }; type desk = { count: number }; interface House extends roof { color: string }; interface Building extends desk { wall: string }; 從這兩個例子來看,type比較像是強化宣告後的物件中的型別、屬性。而interface則是類似於class的用法,可以被繼承使用,他已經變成一個完整的物件/類別。 type與inter

最新文章

key event(1)

mouse event(2)

mouse event(1)

跨裝置events

網易分析- youtube10

網頁分析-ecodazoo

網頁分析-mosne

網頁分析-Labuat

網頁分析-waterlife

網頁分析-Deejo