TypeScript
Arrays & Tuples
Arrays
// Typed Arrays (Using Type Annotations)
let ids: number[] = [1, 2, 3];
// Same as above, but Generic Arrays (Using Array<T>)
// Generics are useful when creating complex types.
let moreIds: Array<number> = [1, 2, 3];
Both forms mean the same thing. number[] is the common choice; Array<T> reads better for complex element types, e.g. Array<string | number>.
ReadonlyArray
The ReadonlyArray is a special type that describes arrays that shouldn’t be changed (Immutable Arrays).
const colorROArray: readonly string[] = ["red", "green", "blue"];
// Or using Generics
const colorROArray2: ReadonlyArray<string> = ["red", "green", "blue"];
colorROArray.push("pink"); // Error: Property 'push' does not exist on type 'readonly string[]'
Tuples
A tuple type is another sort of Array type that knows exactly how many elements it contains and exactly which types it contains at specific positions.
let person: [number, string, boolean] = [1, "Pirate Dev", true];
// Following throw compile errors
let d = person[3]; // Tuple type '[number, string, boolean]' of length '3' has no element at index '3'
Tuples are often used to return several values from a function:
function useCounter(): [number, () => void] {
let count = 0;
return [count, () => count++];
}
const [count, increment] = useCounter();
Named and Optional Elements
Labels make a tuple easier to read; ? marks an element as optional:
type Point = [x: number, y: number, z?: number];
const p2: Point = [1, 2];
const p3: Point = [1, 2, 3];
readonly Tuple Type
Just like arrays, Tuples also have readonly variant.
let person: readonly [number, string, boolean] = [1, "Pirate Dev", true];
// Following throw compile errors
person[2] = false; // Error: Cannot assign to '2' because it is a read-only property
person.push(43); // Property 'push' does not exist on type 'readonly [number, string, boolean]'
