Introduction
We use array type annotations to tell TypeScript what kind of items an array holds. This helps catch mistakes early and makes code easier to understand.
let arrayName: type[]; // or let arrayName: Array<type>;
let numbers: number[] = [1, 2, 3];
let fruits: Array<string> = ['apple', 'banana'];
let emptyArray: boolean[] = [];let mixed: (number | string)[] = [1, 'two', 3];
function printColors(colors: string[]): void { for (const color of colors) { console.log(color); } } const favoriteColors: string[] = ['red', 'green', 'blue']; console.log('Colors before adding:'); printColors(favoriteColors); favoriteColors.push('yellow'); console.log('Colors after adding:'); printColors(favoriteColors);
type[] or Array<type>.let nums: number[]; uses number[], which is correct. let nums: number; declares a single number, not an array. let nums: [number]; declares a tuple with one number, not a general array. let nums: Array; is missing the type inside Array<>.type[] or Array<type> for arrays [OK]Array<type>, with angle brackets <>.let names: Array<string>; correctly uses Array<string>. let names: Array[string]; uses square brackets instead of angle brackets, which is invalid. let names: string[]; is valid syntax but uses the shorthand, not generic syntax. let names: Array(); uses parentheses, which is incorrect.let fruits: string[] = ['apple', 'banana', 'cherry']; console.log(fruits[1]);
fruits[0] is 'apple', fruits[1] is 'banana'.fruits[1], which is 'banana'.let scores: Array<number> = [10, 20, '30'];
Array<number>, so all elements must be numbers.30.let matrix: boolean[][]; uses shorthand nested arrays boolean[][], which is correct but not the generic syntax. let matrix: Array<boolean>; is a simple array of booleans, not nested. let matrix: Array; uses generic syntax for nested arrays: Array<Array<boolean>>, which is correct. let matrix: boolean[]; is a simple array of booleans.let matrix: Array; is the best fit.Pass the test and this pattern moves unknown