TypeScript - 數組


在 TypeScript 中,數組類型有多種定義方式,比較靈活。

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

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

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 類型的參數,所以報錯了。

接口也可以用來描述數組:
interface NumberArray {
    [index: number]: number;
}
let fibonacci: NumberArray = [1, 1, 2, 3, 5];

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

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

let list: any[] = ['Xcat Liu', 25, { website: 'http://xcatliu.com' }];
類數組
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'.

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

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

 數組里的元素也可以是接口里定義的

app: Info[] = [];     //  這里數組的每一項需要滿足{a: number, b: string}這種類型,這里定義app是一個空數組
app = [{a: 1, b: 'b'}]

interface info{   // info是一個接口
    a: number
    b: string
}

 


免責聲明!

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



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