Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 为什么解构数组项会导致联合类型?_Typescript - Fatal编程技术网

Typescript 为什么解构数组项会导致联合类型?

Typescript 为什么解构数组项会导致联合类型?,typescript,Typescript,如果我有: 常量对:[字符串,数字][]=[[a',1],[b',2]]; //为什么这种类型不仅仅是[string,number][]? 常量x:string | number[][]=对 .map[s,n]=>[s,n*2]; 为什么我最终会使用联合类型?作为参考,在各种问题中都提到了这一点,如和 编译器看到[s,n*2],必须为它推断一个类型,因为回调没有显式注释。一般来说,编译器假定数组的内容以后可能会被修改,并且元素的顺序无关紧要。下面是一些有人可能编写的有效代码: const myA

如果我有:

常量对:[字符串,数字][]=[[a',1],[b',2]]; //为什么这种类型不仅仅是[string,number][]? 常量x:string | number[][]=对 .map[s,n]=>[s,n*2];
为什么我最终会使用联合类型?

作为参考,在各种问题中都提到了这一点,如和

编译器看到[s,n*2],必须为它推断一个类型,因为回调没有显式注释。一般来说,编译器假定数组的内容以后可能会被修改,并且元素的顺序无关紧要。下面是一些有人可能编写的有效代码:

const myArray = [0, 1, "two", 3, "four"];
myArray[2] = 2;
myArray[3] = "three";
myArray.push(Math.random() < 0.5 ? 5 : "five");
console.log(myArray); // [0, 1, 2, "three", "four", 5] or something
const断言本质上告诉编译器推断出它所能推断的最窄的类型;它假设数组的内容永远不会更改,而不是假设数组可能会被修改或重新排序,因此得到一个只读元组。这能满足你的需要吗?或者,您可以显式注释回调函数的返回类型:

const y = pairs.map(([s, n]): [string, number] => [s, n * 2]);
// const y: [string, number][]
这将为您提供所需的类型,而无需readonly

好吧,希望这会有帮助;祝你好运


极大的帮助;你的回答提供了一个完整的解释,我不知道常量表达式,这将是非常有用的
const y = pairs.map(([s, n]): [string, number] => [s, n * 2]);
// const y: [string, number][]