Z
Z
zlodiak2020-04-20 00:15:23
typescript
zlodiak, 2020-04-20 00:15:23

Why is it allowed to add a value to a tuple?

There is this code:

let qwe: [string, number];
qwe = ['qqq', 4]
qwe.push(7);
qwe[1] = 44
qwe[2] = 77

console.log(qwe)


He works out. This can be seen from the console output, which contains no error messages. But on the other hand, vscode underlines the line in red: This indicates the presence of some kind of error. Please explain why such an ambiguous situation arises and who to trust the console or IDE? LIVE DEMO
qwe[2] = 77


Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-04-20
@bingo347

Because a tuple in ts is a subtype of an array, and the type system of ts is so poor that it cannot be expressed through it that some methods of the main type are not available on the subtype.

qwe[2] = 77
There are just 2 type errors at once:
firstly, 77 cannot be assigned to the undefined type - since [string, number]- this is quite a sugar over the type
{readonly length: 2; 0: string; 1: number} & Readonly<typeof Array.prototype>

secondly, 2 in the index again cannot be inserted into the type'length' | 0 | 1 | keyof typeof Array.prototype

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question