TypeScript Rest参数
在TypeScript中,我们可以使用rest参数语法将不确定数量的参数指定为数组。无论如何定义函数,都可以使用rest参数以任意数量的参数调用函数。
rest参数允许我们向函数传递零个或任意数量的指定类型的参数。在函数定义中,我们指定函数参数时,rest参数应始终位于最后,否则TypeScript编译器将报错。
语法: 以下是rest参数的语法:
function function_name(...rest: type[]) {
// Type of the is the type of the array.
}
示例1: 使用剩余参数求数字的平均值。下面的代码是一个剩余参数的示例,我们可以传入任意数量的参数,然后输出数字的平均值。
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));
输出:
Average of the given numbers is : 30
Average of the given numbers is : 5.5
Average of the given numbers is : 4
示例2: 这个示例中,rest参数的类型是字符串。它接受字符串类型的参数。在下面的程序中有两个参数,rest参数应该总是置于最后。我们使用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: 如果我们在开头定义剩余参数会发生什么?它只会接受一个参数,而不是接受无限数量的参数。 TypeScript编译器会报错,并且该函数将毫无用处。
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/
极客教程