
Ts Arrays in TypeScript
In TypeScript, arrays are a collection of elements of the same type (or a union of types). TypeScript enforces type safety, ensuring that the array only contains elements of the specified type.
Defining Arrays in TypeScript
- Using the Array Generic:
let arrayName: Array<Type>;
- Using Square Bracket Notation:
let arrayName: Type[];
Examples
1. Single-Type Arrays
// Using Array Genericlet numbers: Array<number> = [1, 2, 3];// Using Square Bracket Notationlet strings: string[] = ["apple", "banana", "cherry"];
2. Union-Type Arrays
let mixed: (number | string)[] = [1, "two", 3, "four"];
3. Readonly Arrays
Readonly arrays prevent modification of their elements.
let readonlyNumbers: ReadonlyArray<number> = [1, 2, 3];// readonlyNumbers.push(4); // Error: Cannot modify a readonly array
Array Operations in TypeScript
TypeScript supports standard array methods such as push
, pop
, map
, filter
, and more.
Example:
let numbers: number[] = [1, 2, 3, 4];// Add an elementnumbers.push(5);// Remove the last elementnumbers.pop();// Map over the arraylet doubled = numbers.map((n) => n * 2); // [2, 4, 6, 8]// Filter the arraylet evenNumbers = numbers.filter((n) => n % 2 === 0); // [2, 4]
Special Array Types
1. Tuples
Tuples are fixed-length arrays where each element can have a different type.
let tuple: [string, number, boolean] = ["Alice", 25, true];
2. Multi-Dimensional Arrays
let matrix: number[][] = [ [1, 2, 3], [4, 5, 6], [7, 8, 9],];
3. Arrays with Optional Elements
let optionalArray: (number | undefined)[] = [1, undefined, 3];
Type Checking and Inference
TypeScript infers the type of an array if initialized with values:
let inferredArray = [1, 2, 3]; // inferred as number[]
You can also explicitly declare the type to avoid inference issues:
let explicitArray: string[] = ["hello", "world"];
Examples of Common Use Cases
1. Looping Through Arrays
let fruits: string[] = ["apple", "banana", "cherry"];for (let fruit of fruits) { console.log(fruit);}fruits.forEach((fruit) => console.log(fruit));
2. Function Parameters and Return Types
function getFirstElement(arr: number[]): number | undefined { return arr[0];}let first = getFirstElement([10, 20, 30]); // 10
TypeScript vs JavaScript Arrays
- Type Safety: TypeScript enforces that the array elements match the specified type.
- Readonly Feature: TypeScript allows defining arrays as readonly.
- Advanced Types: Supports tuples, union types, and intersections for arrays.