Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

An array in TypeScript is an ordered, iterable data structure that enforces strict type checking on its elements. It ensures that all items within the collection conform to a predefined type signature, preventing runtime type errors inherent to dynamically typed JavaScript. TypeScript provides two syntactically equivalent approaches to declare an array type: the square bracket notation and the generic array type.
// Square bracket notation (Standard convention)
let numericArray: number[] = [1, 2, 3];

// Generic Array type
let stringArray: Array<string> = ["a", "b", "c"];

Complex Type Arrays

Arrays can enforce types for complex structures, including interfaces, type aliases, and union types. When using union types, parentheses are required to dictate the order of operations.
// Union types
let mixedArray: (string | number)[] = ["hello", 42];

// Interface typing
interface User {
    id: number;
    name: string;
}
let users: User[] = [{ id: 1, name: "Alice" }];

Multi-dimensional Arrays

Multi-dimensional arrays are declared by chaining the square bracket notation or nesting the generic syntax. This enforces the type signature across nested iterable levels.
// 2D Array using bracket notation
let matrix: number[][] = [
    [1, 2],
    [3, 4]
];

// 2D Array using generic notation
let genericMatrix: Array<Array<number>> = [
    [1, 2],
    [3, 4]
];

Readonly Arrays

TypeScript introduces immutability at the type level via the readonly modifier or the ReadonlyArray<T> generic. These types strip away mutating methods (e.g., push, pop, splice) and prevent index assignment during compilation.
// Using the readonly modifier
let immutableNumbers: readonly number[] = [1, 2, 3];

// Using the ReadonlyArray generic
let immutableStrings: ReadonlyArray<string> = ["a", "b"];

// Compilation Errors:
// immutableNumbers[0] = 99; 
// immutableNumbers.push(4); 

Type Inference

If an array is initialized without an explicit type annotation, the TypeScript compiler infers the type signature based on the union of the types of the initial elements.
// Inferred as (number | string | boolean)[]
let inferredArray = [1, "two", true]; 

Tuples (Fixed-Length Arrays)

A tuple is a specialized array subtype in TypeScript. While standard arrays represent an unbounded collection of uniform (or union) types, a tuple enforces both a fixed length and a specific type at each positional index.
// Tuple declaration
let record: [string, number, boolean] = ["active", 100, true];

// Optional tuple elements
let optionalRecord: [string, number?] = ["pending"];

// Rest elements in tuples
let spreadTuple: [string, ...number[]] = ["scores", 98, 85, 100];
Master TypeScript with Deep Grasping Methodology!Learn More