In TypeScript, arrays can be strictly typed by specifying the type of elements using the type[] notation or Array<type>. For example:
let arr: number[] = [1, 2, 3];
Tuples are arrays with a fixed length and types for each element:
let tuple: [string, number] = ["age", 30];
Pitfalls:
push is not forbidden, but the result goes beyond the guaranteed typing.Can tuples in TypeScript contain a variable number of elements, and how will this affect typing?
Answer: Yes, tuples can contain rest elements using the ... syntax, but still require strict typing for the remaining elements:
let tuple: [string, ...number[]] = ["id", 10, 20, 30];
However, the elements before ... must be specified, and the type for the remaining array must be uniform.
Story
In an e-commerce project, a developer tried to save more than two elements in a tuple [string, number] using push. This did not raise an error at compile time, but broke the function that expected exactly two elements, leading to errors when parsing orders.
Story
A function returned a tuple [string, number], however, the consumer expected an array of strings. The type mismatch caused a hard-to-detect error, resulting in incorrect values being deployed to production.
Story
During the migration of code from JavaScript to TypeScript, arrays were used instead of tuples for returning multiple values of different types. This violated strict typing and led to bugs in subsequent code that relied on the order and type of values.