TS學習隨筆(四)->數組的類型


少俠們,今天我們繼續來搞一搞TS

今天我們要來看一看TS中數組的定義是個什么鬼樣子

數組的類型:

在 TypeScript 中,數組類型有多種定義方式,比較靈活。下面我們來看看有哪些定義方法

  「類型 + 方括號」表示法:

    最簡單的方法是使用「類型 + 方括號」來表示數組:  

let  tsArray: number[] = [1,1,2,3,4]

 

    數組中的項中不允許出現其他類型

let fibonacci: number[] = [1, '1', 2, 3, 5];

// index.ts(1,5): error TS2322: Type '(number | string)[]' is not assignable to type 'number[]'.
//   Type 'number | string' is not assignable to type 'number'.
//     Type 'string' is not assignable to type 'number'.

    上例中,[1, '1', 2, 3, 5] 的類型被推斷為 (number | string)[],這是聯合類型和數組的結合。

    數組的一些方法的參數也會根據數組在定義時約定的類型進行限制:

let fibonacci: number[] = [1, 1, 2, 3, 5];
fibonacci.push('8');

// index.ts(2,16): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

    上例中,push 方法只允許傳入 number 類型的參數,但是卻傳了一個 string 類型的參數,所以報錯了。  

 

  數組泛型:  

    也可以使用數組泛型(Array Generic) Array<elemType> 來表示數組:  

let fibonacci: Array<number> = [1, 1, 2, 3, 5];

    關於泛型,大家可以先仔細學習一下,后面我們也會學到

 

  用接口表示數組:

interface NumberArray {
       [index:number]: number;         
}
let fibonacci: NumberArray = [1,1,2,3,4]

    NumberArray 表示:只要 index 的類型是 number,那么值的類型必須是 number

 

 

 

  any 在數組中的應用

    一個比較常見的做法是,用 any 表示數組中允許出現任意類型:

let list: any[] = ['Xcat Liu', 25, { website: 'http://xcatliu.com' }];

 

  類數組(特別注意)

    類數組(Array-like Object)不是數組類型,比如 arguments

function sum() {
    let args: number[] = arguments;
}

// index.ts(2,7): error TS2322: Type 'IArguments' is not assignable to type 'number[]'.
//   Property 'push' is missing in type 'IArguments'.

 

    事實上常見的類數組都有自己的接口定義,如 IArgumentsNodeListHTMLCollection 等:

function sum() {
    let args: IArguments = arguments;
}

 

好了,以上就是TS里面的數組類型

 

 

參考文章:https://github.com/xcatliu/typescript-tutorial/blob/master/basics/type-of-array.md


免責聲明!

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



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