简体   繁体   English

函数休息参数和泛型

[英]function rest parameter and generic

i have the following error in my iteration我的迭代中有以下错误

Operator '+=' cannot be applied to types 'number' and 'T'.运算符 '+=' 不能应用于类型 'number' 和 'T'。

i don't no why我不知道为什么

let a: number = 1, b: number = 2, c: number = 3, d: number = 4;
function somme<T>(...nombres: T[]): T {
  let s: number = 0;

  for (let nombre of nombres) {
    s += nombre;
  }
  return s;
}

console.log(a + `  + ` + b + ` = ` + somme<number>(a, b));
// 1 + 2 = 3
console.log(a + `  + ` + b + `  + ` + c + `  = ` + somme<number>(a, b, c));
// 1 + 2 + 3 = 6
console.log(a + `  + ` + b + `  + ` + c + `  + ` + d + `  = ` + somme<number>(a, b, c, d));
// 1 + 2 + 3 + 4 = 10

Thanks you for youre help谢谢你的帮助

You have an error because + operator is restricted for two primary types string and number , you can use it only for these two or subtypes like 1 or abc .你有一个错误,因为+运算符被限制用于两个主要类型stringnumber ,你只能将它用于这两个或子类型,如1abc In your case its visible you want to work with number type only (you have local s of this type), I propose to remove generic type because this function always works with numbers:在您的情况下,它可见您只想使用number类型(您有这种类型的 local s ),我建议删除泛型类型,因为此函数始终适用于数字:

function somme(...nombres: number[]): number {
  let s: number = 0;

  for (let nombre of nombres) {
    s += nombre;
  }
  return s;
}

Eventually you can keep generic (still see no reason), but not for return, as return is a sum, and not the same number you get as argument:最终你可以保持通用(仍然看不到任何理由),但不是为了回报,因为回报是一个总和,而不是你作为参数得到的相同数字:

function somme<T extends number>(...nombres: T[]): number {
  let s: number = 0;

  for (let nombre of nombres) {
    s += nombre;
  }
  return s;
}

You cannot have return type T because it would mean that if you say T = 1 then return would be 1 , and in reality would be sum of all 1 value in the given as argument array, so the sum would be T * arr['length'] and such type is not possible in TS because there is no such thing like type arithmetic operations.你不能有返回类型T因为这意味着如果你说T = 1那么 return 将是1 ,实际上将是给定参数数组中所有1值的总和,所以总和将是T * arr['length']并且这种类型在 TS 中是不可能的,因为没有像类型算术运算这样的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM