fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

[TypeScript] 第1532天 在TypeScript中解释下rest参数的作用及规则

Open haizhilin2013 opened this issue 2 years ago • 2 comments

第1532天 在TypeScript中解释下rest参数的作用及规则

3+1官网

我也要出题

haizhilin2013 avatar Jun 25 '23 20:06 haizhilin2013

  • 一个函数只能有一个rest参数,并且必须是最后一个参数。这是因为rest参数会捕获所有剩余的参数作为一个数组,所以必须在参数列表的末尾来确保不会有参数被漏掉。

  • rest参数的类型声明是一个数组类型

  • 当调用函数时,我们可以传递任意数量的参数给 rest 参数。这些参数会被收集到一个数组中,并在函数内部以数组的形式使用

function sum(...numbers: number[]) {
  let total = 0;
  for (let num of numbers) {
    total += num;
  }
  return total;
}
console.log(sum(1, 2, 3)); // 输出 6
console.log(sum(4, 5, 6, 7, 8)); // 输出 30

13837678992 avatar Jul 06 '23 07:07 13837678992

在TypeScript中,rest参数(也称为剩余参数)用于表示函数参数列表中的不确定数量的参数。使用rest参数,可以将不确定数量的参数聚合为一个数组。下面是关于rest参数的作用及其规则的详细解释:

作用

  1. 处理可变数量的参数:rest参数允许函数接受不定数量的参数,并将这些参数收集到一个数组中,方便处理。
  2. 提高函数的灵活性:通过使用rest参数,函数可以更加灵活,适应不同的调用场景,而不需要定义多个重载或使用复杂的参数解析逻辑。

语法和规则

  1. 定义rest参数:在函数参数列表的最后一个参数前加上三个点(...)即为rest参数。这个参数将捕获所有剩余的参数,并将它们放入一个数组中。

  2. rest参数必须是最后一个参数:在函数参数列表中,rest参数必须是最后一个参数,之后不能再有其他参数。

  3. 类型注解:可以为rest参数指定类型注解,表示数组中元素的类型。

示例代码

基本使用

function sum(...numbers: number[]): number {
  return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3)); // 输出: 6
console.log(sum(10, 20, 30, 40)); // 输出: 100

在上面的示例中,sum函数使用rest参数numbers,该参数是一个由所有传递给函数的数字组成的数组。函数通过调用reduce方法来计算这些数字的和。

与其他参数结合使用

function multiply(factor: number, ...numbers: number[]): number[] {
  return numbers.map(num => num * factor);
}

console.log(multiply(2, 1, 2, 3)); // 输出: [2, 4, 6]
console.log(multiply(5, 10, 20, 30)); // 输出: [50, 100, 150]

在这个例子中,multiply函数接受一个普通参数factor和一个rest参数numbers。函数返回一个新数组,其中每个元素都是原数组元素与factor的乘积。

类型注解

function logMessages(message: string, ...args: string[]): void {
  console.log(message);
  args.forEach(arg => console.log(arg));
}

logMessages('Error:', 'Invalid input', 'Please try again'); 
// 输出:
// Error:
// Invalid input
// Please try again

在这个示例中,logMessages函数接受一个字符串message和任意数量的字符串参数args,并依次输出这些参数。args被注解为string[],表示它是一个字符串数组。

规则总结

  1. Rest参数必须是最后一个参数:你不能在rest参数之后再定义其他参数。
  2. Rest参数类型注解:rest参数的类型注解必须是数组类型,例如:...args: number[]...params: string[]
  3. 调用时展开参数:传递给rest参数的值在调用时会自动展开为单个参数,不需要额外处理。

通过使用rest参数,可以使TypeScript函数更加灵活和易于使用,尤其是在处理不确定数量的参数时。

llccing avatar Jun 26 '24 08:06 llccing