Search code examples
arraystypescriptecmascript-6tuplesdestructuring

Is [number, number] a tuple type?


In the below code,

function f([first, second]: [number, number]){
    console.log(first);
    console.log(second);
}

var input:number[] = [1,2];
f(input);

number[] type variable(input) is passed to f.

Why compiler errors out? Argument of type 'number[]' is not assignable to parameter of type '[number, number]'. Type 'number[]' is missing the following properties from type '[number, number]': 0, 1ts(2345)


Solution

  • TypeScript can be very specific in what it expects to be passed to a method.

    For your example:

    function f([first, second]: [number, number]){
        console.log(first);
        console.log(second);
    }
    

    This will work:

    var x: [number, number] = [1,2];
    
    f([1,2]); // Type is implied:  [number, number]
    f(x);     // Type is explicit: [number, number]
    

    This won't:

    var x = [1,2,3];
    var y = [1,2];
    var z: number[] = [1,2];
    
    f(x); // Type is implied:  number[]
    f(y); // Type is implied:  number[]
    f(z); // Type is explicit: number[]
    

    You told typescript to expect an array containing 2 numbers. That's why it won't accept anything but an array containing 2 numbers.

    You can change the accepted type like this:

    function f([first, second]: number[]){
    // Keep destructuring ^,      ^ but change the accepted type.
        console.log(first);  
        console.log(second);
    }
    

    Then, any of the previous 6 examples will work, as [number, <number...>] are also number[] arrays.