TypeScript 中的 Rest 参数
在 Typescript 中,我们可以使用剩余参数语法将不定数量的参数指定为数组。可以使用 rest 参数使用任意数量的参数调用函数,而不管它是如何定义的。
剩余参数允许我们将零个或任意数量的指定类型的参数传递给函数。在我们指定函数参数的函数定义中,其余参数应该总是最后出现,否则打字稿编译器会引发错误。
语法:下面是 rest 参数的语法:
function function_name(...rest: type[]) {
// Type of the is the type of the array.
}
示例 1:使用 rest 参数的数字平均值。下面的代码是 rest 参数的示例,我们传入任意数量的参数,并将这些数字的平均值显示为输出。
Javascript
function getAverage(...args: number[]) {
var avg = args.reduce(function (a, b) {
return a + b;
}, 0) / args.length;
return avg;
}
// Function call
console.log("Average of the given numbers is : " +
getAverage(10, 20, 30, 40, 50));
console.log("Average of the given numbers is : " +
getAverage(1.5, 3.5, 5.5, 7.5, 9.5));
console.log("Average of the given numbers is : " +
getAverage(2, 4, 6));
Javascript
function Job(Job_title: string,
...people: string[]) {
return people.join(", ") + " are " + Job_title;
}
console.log(Job("mathematicians", "rachel",
"john", "peter"));
console.log(Job("coders", "sarah", "joseph"));
Javascript
function Job(...people: string[],
Job_title: string) {
return people.join(", ") + " are " + Job_title;
}
console.log(Job("rachel", "john", "peter",
"Mathematicians"));
console.log(Job("sarah", "joseph", "coders"));
输出:
Average of the given numbers is : 30
Average of the given numbers is : 5.5
Average of the given numbers is : 4
示例 2:本示例中的其余参数为字符串类型。它接受字符串类型的参数。下面的程序中有两个参数。其余参数应始终位于最后。我们使用 join() 方法通过字符串' , ' 来连接字符串。本例中返回一个简单的字符串。
Javascript
function Job(Job_title: string,
...people: string[]) {
return people.join(", ") + " are " + Job_title;
}
console.log(Job("mathematicians", "rachel",
"john", "peter"));
console.log(Job("coders", "sarah", "joseph"));
输出:
rachel, john, peter are mathematicians
sarah, joseph are coders
示例 3:如果我们在开始时定义 rest 参数会发生什么?它只接受一个参数,而不是接受不定数量的参数。打字稿编译器将引发错误,该函数将毫无用处。
Javascript
function Job(...people: string[],
Job_title: string) {
return people.join(", ") + " are " + Job_title;
}
console.log(Job("rachel", "john", "peter",
"Mathematicians"));
console.log(Job("sarah", "joseph", "coders"));
输出: Typescript 编译器引发错误。
error TS1014: A rest parameter must be last in a parameter list.
76 function Job(...people: string[], Job_title: string) { ... }
参考: https://www.typescripttutorial.net/typescript-tutorial/typescript-rest-parameters/