尝试解构可能长度为 2 的数组时出错

Error while trying to destructure an array of possible length 2

我正在尝试解构一个长度为 2 的数组,但出现打字稿错误:

[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;
        }
    }

我如何告诉打字稿,数组的长度可能是 2?

您还没有将 message 声明为数组;您已将其声明为元组 ([string]) 并且元组具有固定数量的元素。 (请参阅 Basic Types 文档中的 Tuple 部分。)

您可以将其声明为具有两个字符串元素的元组 ([string, string]),但考虑到您正在测试 message.length >= 2,您似乎打算将其声明为字符串数组 (string[]):

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

使用 string[](任意长度的数组)代替 [string]"tuple" 长度限制为 1)作为您的类型。

元组具有特定的长度,可以更轻松地表示分配给特定索引位置的多种类型,例如 [string, number]。同质(单一类型)元组在某些场景中仍然有用(例如在地图中表示对),但并不常见。

另一方面,数组是可变长度的列表,但设计用于仅保存单一类型的引用(即使该类型是联合类型或 any)。如果任何数组的一个索引可以容纳某个值,则每个索引都可以容纳相同类型的值。


TypeScript 代码 (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)

尝试更改 message 变量的类型。字符串数组比单个字符串数组更适合

let message: string[] = execute.params;