Arrays and Tuples
Typing Arrays
To type an array, you append [] to the specific data type that the array is allowed to hold.
// An array strictly holding numbers
let testScores: number[] = [85, 92, 100];
// An array strictly holding strings
let activeUsers: string[] = ["Alice", "Bob", "Charlie"];
// TS Error: Argument of type 'string' is not assignable to parameter of type 'number'.
testScores.push("Zero");
Alternative Generic Syntax
You can also legally define arrays using the generic interface syntax Array<Type>. This does the exact same thing!
let testScores: Array<number> = [85, 92, 100];
Typing Tuples
Standard arrays in JavaScript have variable lengths and can hold combinations of items dynamically. A Tuple is a strictly typed Array where you define exactly what type of data belongs at which specific index, locking the array's exact structural configuration.
// A Tuple definition: [String, Number, Boolean]
let profile: [string, number, boolean];
// Valid assignment
profile = ["Alice", 25, true];
// TS Error: Type 'number' is not assignable to type 'string' at index 0.
profile = [25, "Alice", true];
Common Usage
Tuples are incredibly common when dealing with React Hooks.
// React's useState returns a strict Tuple!
// [Value, DispatchFunction]
const [count, setCount] = useState(0);