TypeScript的开放式函数参数 [英] open-ended function arguments with TypeScript
问题描述
IMO是> TypeScript 语言的主要关注点之一,它支持现有的vanilla JavaScript代码。这是我乍一看的印象。看看以下完全有效的JavaScript函数:
IMO, one of the main concerns of the TypeScript language is to support the existing vanilla JavaScript code. This is the impression I had at first glance. Take a look at the following JavaScript function which is perfectly valid:
注意:我并不是说我喜欢这种方法。我只是说这是一个
有效的JavaScript代码。
Note: I am not saying that I like this approach. I am just saying this is a valid JavaScript code.
function sum(numbers) {
var agregatedNumber = 0;
for(var i = 0; i < arguments.length; i++) {
agregatedNumber += arguments[i];
}
return agregatedNumber;
}
因此,我们使用任意数量的参数来使用此函数:
So, we consume this function with any number of arguments:
console.log(sum(1, 5, 10, 15, 20));
然而,当我尝试使用 TypeScript Playground ,它会产生编译时错误。
However, when I try this out with TypeScript Playground, it gives compile time errors.
我假设这是一个错误。我们假设我们没有兼容性问题。那么,有没有办法用开放式参数编写这种类型的函数?比如C#中的 params
功能?
I am assuming that this is a bug. Let's assume that we don't have the compatibility issues. Then, is there any way to write this type of functions with open-ended arguments? Such as params
feature in C#?
推荐答案
TypeScript的做法这是将省略号运算符( ...
)放在参数名称之前。以上内容将被写为,
The TypeScript way of doing this is to place the ellipsis operator (...
) before the name of the argument. The above would be written as,
function sum(...numbers: number[]) {
var aggregateNumber = 0;
for (var i = 0; i < numbers.length; i++)
aggregateNumber += numbers[i];
return aggregateNumber;
}
这将使用
console.log(sum(1, 5, 10, 15, 20));
这篇关于TypeScript的开放式函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!