# TypeScript 常用型別 - 陣列 (Array) ![image](https://hackmd.io/_uploads/SyBO-P7G0.png) * 不能推入非定義的值 ``` let numbers: number[]=[1,2,3] // 會出錯不能推入非number的值 numbers.push('4'); ``` * 型別自動推斷,因此會出錯 ``` // 型別自動推斷,型別賦予的時候自動推論 let numbers=[1,2,3] numbers.push('4'); ``` * 定義沒有該key,一樣會報錯誤 ``` // 如定義沒有該key,一樣會報錯誤 product.id= 'No2424' ``` ## 寫法 1. 陣列以[]表示,順序表達為內往外,代表陣列內部須為 string ``` const todoList: string[] = ['TODO,'UNDO'] ``` 2. 型別斷言的方式表達 ``` const todoList: Array<string> = ['TODO,'UNDO'] ``` 3. **限制數量**,此方式是限制這個陣列裡面只能有這兩個 string ``` const todoList: [string,string] = ['TODO,'UNDO'] ``` ## 二維陣列 * 內部為string ``` let arr: string[][] =[ ['a'], ['b'] ] ```