{%hackmd BJrTq20hE %} ###### tags: `TypeScript` # TypeScript 的進階操作 Type Interface Enum ## type 什麼是Type,簡單的來說就是自己定義資料的型別 以下的範例代表personalData這個變數內容可以是字串或數字或布林 ``` let personalData: string | number | boolean = "Jack"; ``` 但如果相同union的變數一多,會變得很不好維護。 ``` let personalData1: string | number | boolean = 456; let personalData2: string | number | boolean = false; let personalData3: string | number | boolean = "May"; . . . ``` 這個時候就可以定義type ``` type PersonalData = string | number | boolean let personalData:PersonalData = "Jack"; ``` ### 物件的type 物件一樣可以定義type 範例如下 ``` type personInfoType = { name:string, age:number, isWork:boolean}; const personalInfo: personInfoType = { name:"Jack", age: 42, isWork: true}; ``` ## interface Interface 可以用來定義物件,還有由物件所延伸的型別(例如,陣列、函式) 下方的範例就是定義物件的interface與type很像 ``` interface dataType { name:string age:number } const obj: dataType = { name:"Jack", age:26} ``` 所有元素都是字串的陣列 ``` interface StringArray { [index: number]: string; } ``` ## interface與type的相似與區別 interface與type都具有繼承的特性。 ### interface與type相似處都可以擴充 type的繼承 以下的範例就是type subObj繼承type Obj的寫法 ``` type Obj = { name: string } type subObj = Obj & { age: number } const obj:subObj={ name:"Jack", age:55 } ``` interface的繼承 以下的範例就是interface subObj1繼承interface Obj1的寫法 ``` interface Obj1{ name: string } interface subObj1 extens Obj1{ age: number } const obj1:subObj1 = { name:"May", age:18 } ``` ### interface與type不同處 interface可以合併,type不行 以下的範例就是interface Data的合併 ``` interface Data { name: string } interface Data { age: number } const obj2:Data = { name:"May", age:22 } ``` ## enum 枚舉 enum的作用是用數字表示狀態時,只有前端與後端約定好的數字對應,其他的開發者看到只會是magic number,這個時候就可以使用enum了 ``` enum ProductStatus{ "soldout"=0, "normal"=1, "discoumt"=2, "restock"=3 } let productStatus = 0 if(productStatus = ProductStatus.soldout){ //... } ``` 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up