In TypeScript, arrays are strongly typed, ensuring all elements match a specific type signature and preventing out-of-bounds type mismatches.
T[] (e.g., string[], number[]).Array<T> (e.g., Array<string>, Array<number>).readonly T[] or ReadonlyArray<T> (immutable collections).// Standard typed array
const serverLogs: string[] = [];
serverLogs.push("INFO: Server booted on port 3000");
serverLogs.push("WARN: High CPU utilization detected");
// Generic syntax
const httpStatusCodes: Array<number> = [200, 201, 400, 404, 500];
// Readonly array preventing mutations
const supportedCurrencies: readonly string[] = ["USD", "EUR", "GBP", "JPY"];
// supportedCurrencies.push("CAD"); // Compiler error: Property 'push' does not exist on type 'readonly string[]'
function printLogs(logs: readonly string[]): void {
logs.forEach((log, index) => console.log(`[Line ${index + 1}] ${log}`));
}
printLogs(serverLogs);
readonly T[] for Function Parameters: Ensures functions do not accidentally mutate input array parameters.T[] Bracket Syntax: It is more concise and widely used in the TypeScript community than Array<T>.arr[99] on number[] returns number at compile time, but undefined at runtime if index 99 does not exist. Enable noUncheckedIndexedAccess in tsconfig.json for strict checks.Declare a readonly array of numbers containing [10, 20, 30]. Try modifying index 0 (arr[0] = 50) and note the compiler error.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With