·  阅读 9793

# 招式一和招式二

``````// 招式一

// 招式二：泛型
Array<number>

``````// arrayFibonacci.ts
let arrayFibonacci: number[] = [1, 1, 2, 3, 5, 8];

``````// arrayFibonacci2.ts
let arrayFibonacci2: number[] = [1, 1, '2', false, 5, 8];

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

``````// arrayFibonacci3.ts
let arrayFibonacci3: (number | string | boolean)[] = [1, 1, '2', false, 5, 8];

``````// arrayPush.ts
let arrayPush: Array<number> = [1, 2, 3];
arrayPush.push(5);
arrayPush.push('1');

// 0.0.5/arrayPush.ts:3:16 - error TS2345: Argument of type '"1"' is not assignable to parameter of type 'number'.
// 3 arrayPush.push('1');

# 招式三：接口

``````// arrayInterface.ts
interface ArrayNumber {
[index: number]: number
}

let arrayNumberInterface: ArrayNumber = [1, 1, 2, 3, 5];

# 问：如果数组中想要存放多种类型怎么办？

``````// arrayAny.ts
let arrayAny: any[] = [1, '1', false, { name: 'ts' }, [1, 1, 2]];

// 或
let arrayAny2: Array<any> = [1, '1', false, { name: 'ts' }, [1, 1, 2]];

# 问：对于类数组怎么处理？

``````// arrayArguments.ts
function arrayArguments(){
let args: number[] = arguments;
let args2: Array<number> = arguments;
}

// 0.0.5/arrayArguments.ts:2:9 - error TS2740: Type 'IArguments' is missing the following properties from type 'number[]': pop, push, concat, join, and 24 more.
// 2     let args: number[] = arguments;

// 0.0.5/arrayArguments.ts:3:9 - error TS2322: Type 'IArguments' is not assignable to type 'number[]'.
// 3     let args2: Array<number> = arguments;

``````// arrayArguments2.ts
function arrayArguments2(){
let args: IArguments = arguments;
}