ProgrammingFrontend Developer / TypeScript Developer

How is strict typing of arrays and tuples implemented and why is it used in TypeScript? What are their differences and pitfalls when using them?

Pass interviews with Hintsage AI assistant

Answer

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];
  • Array: allows any number of elements of the same type.
  • Tuple: strictly defines the number and order of types. It enables the creation of structures similar to records or returning values of different types from a function.

Pitfalls:

  • When using array methods (push, pop) on tuples, push is not forbidden, but the result goes beyond the guaranteed typing.
  • Careless expansion of a tuple leads to "unsafe" code.
  • Destructuring tuples in functions: incorrectly specified type or length will result in an error.

Trick Question

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.

Examples of real errors due to ignorance of the nuances of the topic


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.