Explain Arrays in TypeScript
In TypeScript, arrays are used to store a collection of elements of the same type, offering type safety and additional functionality over JavaScript arrays. They can be defined in two ways:
- Square Brackets Notation:
let numbers: number[] = [1, 2, 3, 4];
- Array Generic Type:
let strings: Array<string> = ['a', 'b', 'c'];
Key Features
- Type Safety: Ensures all elements adhere to a specific type.
- Methods: Provides JavaScript array methods with compile-time checks (e.g.,
push
,map
,filter
). - Multi-dimensional Arrays: Supports arrays of arrays.
Example:
let matrix: number[][] = [
[1, 2],
[3, 4],
];
Tuples
TypeScript extends arrays with tuples, allowing fixed-length arrays with specific types for each position:
let tuple: [string, number] = ['age', 25];