TypeScript 陣列
TypeScript 有特定的陣列型別語法。
在我們的JavaScript 陣列章節中瞭解更多關於陣列的資訊。
示例
const names: string[] = [];
names.push("Dylan"); // 無錯誤
// names.push(3); // 錯誤:型別 'number' 的引數不能賦值給型別 'string' 的引數。
自己動手試一試 »
只讀
readonly
關鍵字可以防止陣列被修改。
示例
const names: readonly string[] = ["Dylan"];
names.push("Jack"); // 錯誤:型別 'readonly string[]' 上不存在屬性 'push'。
// 嘗試移除 readonly 修飾符看看是否有效?
自己動手試一試 »
型別推斷
如果陣列有值,TypeScript 可以推斷出陣列的型別。
示例
const numbers = [1, 2, 3]; // 推斷為 number[] 型別
numbers.push(4); // 無錯誤
// 註釋掉下面的行以檢視成功的賦值
numbers.push("2"); // 錯誤:型別 'string' 的引數不能賦值給型別 'number' 的引數。
let head: number = numbers[0]; // 無錯誤
自己動手試一試 »