Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while trying to destructure an array of possible length 2

I am trying to destructure an array of length 2, but I get a typescript error:

[ts] Tuple type '[string]' with length '1' cannot be assigned
to tuple with length '2'.

    let output = {status: false};
    if(execute.permission) {
        let message: [string] = execute.params;
        if(message.length >= 2) {
            // Destructuring follows
            [output['position'], output['message']] = message;
        }
    }

How do I tell typescript, that the array could possiblly be of length 2?

like image 511
Suhail Gupta Avatar asked Mar 31 '17 01:03

Suhail Gupta


People also ask

How do you Destructure an array of objects?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.

What is array Destructuring in JavaScript?

Destructuring in JavaScript is a simplified method of extracting multiple properties from an array by taking the structure and deconstructing it down into its own constituent parts through assignments by using a syntax that looks similar to array literals.


2 Answers

You've not declared message as an array; you've declared it as a tuple ([string]) and tuples have a fixed number of elements. (See the Tuple section in the Basic Types documentation.)

You could declare it as a tuple that has two string elements ([string, string]), but given that you are testing message.length >= 2 it seems likely you intended to declare it as a string array (string[]):

let output = {status: false};
if(execute.permission) {
    let message: string[] = execute.params;
    if(message.length >= 2) {
        // Destructuring follows
        [output['position'], output['message']] = message;
    }
}
like image 145
cartant Avatar answered Oct 22 '22 15:10

cartant


Use string[] (an array of any length) instead of [string] (a "tuple" limited to length 1) as your type.

Tuples have a specific length and make it easier to represent multiple types assigned to specific index positions, like [string, number]. Homogenous (single-type) tuples are still useful in some scenarios (such as representing pairs in a map), but are not as common.

Arrays, on the other hand, are lists of variable length but are designed to hold only references of a single type (even if that type is a union type or any). If one index of any array can hold a certain value, every index can hold that same kind of value.


TypeScript Code (Playground Link)

let execute = { permission: true, params: ['a', 'b']}


let output = { status: false };
    if(execute.permission) {
        let message: string[] = execute.params;
        if(message.length >= 2) {
            // Destructuring follows
            [output['position'], output['message']] = message;
        }
}

console.log(output)
like image 6
gyre Avatar answered Oct 22 '22 15:10

gyre