Javascript typescript数组声明是否需要spread/rest运算符?
通读如下代码:Javascript typescript数组声明是否需要spread/rest运算符?,javascript,typescript,Javascript,Typescript,通读如下代码: export function printAdd(...numbers: number[]) { alert(`Adding the numbers: ${numbers.join(', ')}`); } 是否需要编号中的..。IIUC这意味着数字是一个数组,但我们也在声明使用number[],所以我们似乎是在重复使用 是。。。有必要吗 没有,但是这个问题的答案完全取决于您对参数的预期用途 在您引用的示例中,…表示一个错误。使用此选项将对在指定类型的数组中调用函数时指定
export function printAdd(...numbers: number[]) {
alert(`Adding the numbers: ${numbers.join(', ')}`);
}
是否需要编号中的..
。IIUC这意味着数字是一个数组,但我们也在声明使用number[]
,所以我们似乎是在重复使用
是。。。有必要吗
没有,但是这个问题的答案完全取决于您对参数的预期用途
在您引用的示例中,…
表示一个错误。使用此选项将对在指定类型的数组中调用函数时指定的所有参数进行分组(在本例中,类型为number
)。考虑下面的示例函数和调用:
export function printAdd(...numbers: number[]) {
alert(`Adding the numbers: ${numbers.join(', ')}`);
}
printAdd(1, 2, 3); // Valid because there are 0 or more arguments of type number
printAdd([1, 2, 3]); // Not valid because there is a single argument and it is of type number[]
不使用rest参数向编译器表明函数希望接收类型为number[]
的单个参数
export function printAdd(numbers: number[]) {
alert(`Adding the numbers: ${numbers.join(', ')}`);
}
printAdd(1, 2, 3); // Not valid because there are 3 arguments of type number
printAdd([1, 2, 3]); // Valid because there is a single argument of type number[]
通过分析Typescript编译器的输出,这一点变得更加明显。编译后,第一个示例变成:
// COMPILER OUTPUT
function printAdd() {
var numbers = [];
for (var _i = 0; _i < arguments.length; _i++) {
numbers[_i] = arguments[_i];
}
alert("Adding the numbers: " + numbers.join(', '));
}
参数
对象未被使用,数字
是一个数组
,因此数组。原型
方法可立即使用。该…
表示您调用打印添加(1,2,3)
。如果没有它,您可以像printAdd([1,2,3])
那样调用它。那么本质上它将传入的数组分解为参数?IIUC printAdd([1,2,3])也会这样做吗?它只是语法上的糖分。反过来说。它接受参数
,并将它们组成一个适当的数组。我的意思是,编译器也会捕捉到你用字符串或其他类型调用它时所做的任何调用!!
// COMPILER OUTPUT
function printAdd(numbers) {
alert("Adding the numbers: " + numbers.join(', '));
}