數組合並了相同類型的對象,而元組(Tuple)合並了不同類型的對象。
簡單的例子
定義一對值分別為 string
和 number
的元組:
let xcatliu: [string, number] = ['Xcat Liu', 25]
當賦值或訪問一個已知索引的元素時,會得到正確的類型:
let xcatliu: [string, number]; xcatliu[0] = 'Xcat Liu'; xcatliu[1] = 25; xcatliu[0].slice(1); xcatliu[1].toFixed(2);
也可以只賦值其中一項:
let xcatliu: [string, number];
xcatliu[0] = 'Xcat Liu';
但是當直接對元組類型的變量進行初始化或者賦值的時候,需要提供所有元組類型中指定的項。
let xcatliu: [string, number];
xcatliu = ['Xcat Liu', 25];
越界的元素
let xcatliu: [string, number]; xcatliu = ['Xcat Liu', 25]; xcatliu.push('http://xcatliu.com/'); xcatliu.push(true); // index.ts(4,14): error TS2345: Argument of type 'boolean' is not assignable to parameter of type 'string | number'. // Type 'boolean' is not assignable to type 'number'.