Quick Overview
`string[]` is any number of strings; `[string, number]` is exactly two, in that order. `readonly` removes the mutating methods at compile time, so `push` becomes a type error rather than a runtime surprise.
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!
TypeScript erases entirely at build time, so a `string` annotation produces no runtime check whatsoever. A value arriving from an API is whatever the server actually sent, regardless of what the annotation claims.
`let x = "GET"` infers `string` because the binding can change; `const x = "GET"` infers the literal `"GET"`. That widening rule is why object properties need `as const` to stay narrow.
`?` makes a property optional, which adds `undefined` to its type rather than removing the key. That is why reading it still needs a check even after the shape is declared.
Average 5.0 by 1 learner