New elements are added after typescript declares federated type tuples

just read the document ts when I saw that the tuple was out of bounds, I tried the following

let x: [string, number];
x = ["hello", 10];
:
x[3] = "world"; // OK, (string | number)
console.log(x[5].toString()); // OK, "string"  "number"  toString

x[6] = true; // Error, (string | number)

will report an error here, indicating that the third index value of an array of length 2 cannot be changed directly. Try the push method of another tutorial , and find that it can be inserted successfully, but still cannot be accessed through the index, nor can you change the tuple length property

.

I feel a little confused. Ts is a js superset. I feel that I can"t change the array element directly. After push, the element has been inserted but cannot be accessed. What"s going on? ask for advice

.
Jul.04,2022

the official documentation is not updated on this point.

in fact, after Typescript 2.7 (in the Fixed Length Tuples section), the definition of Tuple has become an array of limited length.

interface NumStrTuple extends Array<number | string> {
    0: number;
    1: string;
    length: 2; // using the numeric literal type '2'
}

so you can't cross the line anymore.

The static type of

typescript is not strongly typed, and even if it is declared as an array of length 2, it can still be push because it is always js. So what typescript can do is to restrict you to continue to do other operations outside the constraints, even though you are beyond the constraints on the array.

Menu