In TypeScript, you can define an array in multiple ways. Here are the three most common methods to define an array:
1. Using square bracket ‘[]‘ notation:
let arr1: number[] = [1, 2, 3, 4, 5];
let arr2: string[] = ['one', 'two', 'three', 'four', 'five'];
2. Using generic ‘Array‘ type notation:
let arr3: Array<number> = [1, 2, 3, 4, 5];
let arr4: Array<string> = ['one', 'two', 'three', 'four', 'five'];
3. Using an angle-bracket type assertion:
let arr5 = <number[]>[1, 2, 3, 4, 5];
let arr6 = <Array<string>>['one', 'two', 'three', 'four', 'five'];
All of these methods create and define an array with specified types. It’s usually recommended to use the first or the second way because they are more explicit and, in the case of the first one, more concise.
Here is a comparison table of these array definition methods:
| Notation Type | Syntax | Example |
|---|---|---|
| Square Bracket | dataType[] |
let arr: number[] = [1, 2, 3]; |
| Generic Array | Array<dataType> |
let arr: Array<number> = [1, 2, 3]; |
| Angle-Bracket Type Assertion | <dataType[]> |
let arr = <number[]>[1, 2, 3]; |
When working with multidimensional arrays, you can define them as follows:
// Two-dimensional array of numbers
let matrix: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
In this example, the type ‘number[][]‘ denotes a two-dimensional array of numbers. You can do the same with other data types and other dimensions.