简体   繁体   中英

function rest parameter and generic

i have the following error in my iteration

Operator '+=' cannot be applied to types 'number' and '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 . 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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