Array types can be defined in a variety of ways, so it’s very flexible. Let’s take a look.
Move one and move two
/ / formsType []// Generics
Array<number>
Copy the code
Take the familiar Fibonacci sequence
// arrayFibonacci.ts
let arrayFibonacci: number[] = [1.1.2.3.5.8];
Copy the code
Q: What if there are multiple types in the array assigned above?
// 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'.
Copy the code
Error ❌ due to ‘2’, false is not assigned to a pure numeric type, to be compatible with a union type (as given in the error message)?
// arrayFibonacci3.ts
let arrayFibonacci3: (number | string | boolean) [] = [1.1.'2'.false.5.8];
Copy the code
We know that arrays have many methods. How about pushing a string?
// arrayPush.ts
let arrayPush: Array<number> = [1.2.3];
arrayPush.push(5);
arrayPush.push('1');
// arrayPush. Ts :3:16 - error TS2345: Argument of type '"1"' is not assignable to parameter of type 'number'.
// 3 arrayPush.push('1');
Copy the code
It seems necessary to pass in the numbers.
Move 3: interface
// arrayInterface.ts
interface ArrayNumber {
[index: number] :number
}
let arrayNumberInterface: ArrayNumber = [1.1.2.3.5];
Copy the code
The above example shows that the value must be of type number as long as index is of type number.
Q: What if you want to store multiple types in an array?
// arrayAny.ts
let arrayAny: any[] = [1.'1'.false, { name: 'ts'},1.1.2]]./ / or
let arrayAny2: Array<any> = [1.'1'.false, { name: 'ts'},1.1.2]].Copy the code
Q: What about class arrays?
Type[] = Type[]
// 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: "- error TS2322: Type 'IArguments' is not assignable to Type' number [] '.
// 3 let args2: Array
= arguments;
Copy the code
Class arrays are not as simple as you might think. IArguments is a built-in object, which I’ll talk about in the next article.
// arrayArguments2.ts
function arrayArguments2(){
let args: IArguments = arguments;
}
Copy the code
This code Github
You can…
Typescript object types – interfaces
Next: Typescript function types
Contents: A primer to Typescript’s short book