ProgrammingFullstack Developer

How does array typing work in TypeScript, how to correctly declare arrays with different type elements, and what are the ways to describe them using tuples? Provide examples and explain possible errors associated with working with such structures.

Pass interviews with Hintsage AI assistant

Answer.

In TypeScript, arrays are described in two main ways: type[] and Array<type>. For arrays with elements of different types, union types or tuples can be used, which allow you to describe a fixed set of elements of different types and quantities.

Array declarations:

let numbers: number[] = [1, 2, 3]; let strings: Array<string> = ['a', 'b', 'c'];

Array with different type elements:

let mixed: (string | number)[] = [1, 'a', 2];

Tuples:

let tuple: [string, number, boolean] = ['hello', 42, true];

Tuples are more convenient to work with when a fixed structure is expected (for example, returning several different typed values from a function), while arrays are more suitable when the number and type of elements may vary or are unknown in advance.

Trick question.

Can you add elements to a tuple of length N using push after defining it? How does it affect typing?

Answer: Yes, you can push to a tuple — the compiler allows this, although it violates the assumption of the tuple’s limited length. The types of new elements will be cast to the union of all possible types of the tuple elements:

let tuple: [number, string] = [42, 'foo']; tuple.push(true); // OK! tuple now: [number, string, boolean], but the type did not update and there is no error! console.log(tuple); // [42, 'foo', true]

Therefore, working with tuples and their mutability needs to be controlled manually or made readonly.

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


Story

A developer described a function that returns a tuple [number, string], but then started adding elements to the result using push. This led to a type mismatch: subsequent code expected exactly two elements of specific types but got an array of variable length, causing runtime errors when unpacking values and accessing nonexistent indices.


Story

An array of different type values was stored using an array any[], considering it a universal solution. As a result, TypeScript stopped checking type correctness, and the application logic began to "break" due to incorrect type conversions that did not raise compilation errors.


Story

In a project, an array was described either via type[] or Array<type> — but in some places the declaration let arr: any[] was allowed (to work "with anything"). This led to uncontrolled transformations, any array was accepted by the function, causing runtime errors when trying to call incorrect methods for elements of different types.