Master typed array lists, fixed-length tuples, and readonly modifiers to enforce immutable data structures in TypeScript.
Discover how TypeScript infers types automatically and how let versus const declarations shape wide types versus narrow literal types.
In JavaScript, arrays can hold mixed data types indiscriminately. TypeScript allows you to enforce strict element types on array lists and fixed-length Tuples.
Define arrays using type[] or generic Array<type> syntax:
const scores: number[] = [95, 82, 88];
const usernames: Array<string> = ["Alex", "Sarah", "Maria"];
// Union arrays
const mixedList: (string | number)[] = ["DevLoom", 100];
A Tuple is a specialized array with a fixed number of elements where each position has a specific data type:
// Tuple: [HTTPCode, StatusMessage]
type ResponsePair = [number, string];
const okResponse: ResponsePair = [200, "OK"];
const notFound: ResponsePair = [404, "Not Found"];
// Invalid tuple assignment:
// const badResponse: ResponsePair = ["OK", 200]; // Error: Type string is not assignable to type number
Prevent array mutation by marking arrays or tuples as readonly:
const immutableCoordinates: readonly [number, number] = [37.7749, -122.4194];
// immutableCoordinates[0] = 0; // Error: Cannot assign to read-only property
// immutableCoordinates.push(10); // Error: Property 'push' does not exist on readonly tuple
.push() on a non-readonly tuple passes compile checks unless marked with readonly! Always use readonly for strict immutable tuples.(string | number)[] means an array containing strings and numbers, whereas string[] | number[] means an array of ALL strings OR an array of ALL numbers!Use tuples for structured fixed pairs. Next, let's explore Object Types and Type Aliases!