TypeScript - 元組


數組合並了相同類型的對象,而元組(Tuple)合並了不同類型的對象。定義一對值分別為 stringnumber 的元組:

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] = ['Xcat Liu'];
 
// index.ts(1,5): error TS2322: Type '[string]' is not assignable to type '[string, number]'.
// Property '1' is missing in type '[string]'.
 
let xcatliu: [string, number];
xcatliu = ['Xcat Liu'];
xcatliu[1] = 25;
 
// index.ts(2,1): error TS2322: Type '[string]' is not assignable to type '[string, number]'.
// Property '1' is missing in type '[string]'.

當添加越界的元素時,它的類型會被限制為元組中每個類型的聯合類型:

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'.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM