An ancestor is structurally similar to an array, as you will see in a moment.

For example

// tuple.ts
let tuple: [string.number];
tuple = ['pr'.30];

let tuple1_1: [string.number] = ['pr'.30];

let tuple1_2: [string.number] = ['pr'];

let tuple1_3: [string.number];
tuple1_3 = ['pr'.30.18];


// 0.0.8/ tupl. ts:6:5 - error TS2741: Property '1' is missing in type '[string]' but required in type '[string, number]'.
    // 6 let tuple1_2: [string, number] = ['pr'];
     
// 0.0.8/ tupl. ts:9:1 - error TS2322: Type '[string, number, number]' is not assignable to Type '[string, number]'.
    // Types of property 'length' are incompatible.
    // Type '3' is not assignable to type '2'.
    // 9 tuple1_3 = ['pr', 30, 18];
Copy the code

As you can see from the example, when you define and assign directly to a variable type, you can’t do more or less.

Q: it’s definitely not possible to pass more, can you pass less?

At the beginning of this article we said that a primitive is similar to an array structure. Try subscript assignment

// tuple2.ts
let tuple2: [string.number];
tuple2[0] = 'pr';

let tuple2_1: [string.number];
tuple2_1[1] = 30;
Copy the code

This wave operates 666.

The new element

// tuple3.ts
let tuple3: [string.number] = ['pr'.30];
tuple3.push(18);
tuple3.push('pr 18');

tuple3.pop();
tuple3.unshift('pr is a jser');
tuple3.unshift(null);
tuple3.unshift(undefined);

tuple3.unshift(false);

// 0.0.8/tuple3.ts:10:16 - error TS2345: Argument of type 'false' is not assignable to parameter of type 'string | number'.
    // 10 tuple3.unshift(false);
Copy the code

Can be found that adding elements of type can be only string | number (add a false error), the next word tuple type can only add elements is a tuple type of joint type.

This code Github

You can…

Previous: Typescript built-in objects

Next: Typescript enumerations

Contents: A primer to Typescript’s short book