[英]How to use typescript to return the sum of all items of an imported array type?
I am stuck on making a method that is supposed to follow the following guidelines:我坚持制作一种应该遵循以下准则的方法:
sumMass( items: Payload[] ): number Returns the sum of all items using each item's massKg property sumMass( items: Payload[] ): number 使用每个项目的 massKg 属性返回所有项目的总和
Payload is an import from another typescript file that looks like有效负载是从另一个 typescript 文件导入的,看起来像
export interface Payload {
massKg: number;
}
here is the code i have for my Rocket class that is supposed to accept items of type Payload array and give a number output.这是我的 Rocket class 的代码,它应该接受有效载荷数组类型的项目并给出一个数字 output。 I keep getting this error
我不断收到此错误
Rocket.ts(20,12): error TS2365: Operator '+=' cannot be applied to types 'number' and 'Payload'. Rocket.ts(20,12):错误 TS2365:运算符 '+=' 不能应用于类型 'number' 和 'Payload'。
import { Payload } from './Payload';
import { Astronaut } from './Astronaut';
import { Cargo } from './Cargo';
export class Rocket implements Payload {
name: string;
massKg: number;
totalCapacityKg: number;
cargoItems: Cargo[] = [];
astronauts: Astronaut[] = [];
constructor(name: string, totalCapacityKg: number,){
this.name = name;
this.totalCapacityKg = totalCapacityKg;
}
sumMass(items: Payload[]): number {
let sum: number = 0;
for(let i = 0; i < items.length; i++){
sum += items[0];
}
return sum;
}
}
let myRocket = new Rocket('rocket', 7);
console.log(myRocket.name);
console.log(myRocket.sumMass([]));
I'm just not sure how to use the interface as an array or how to go about constructing this method any longer.我只是不知道如何将接口用作数组或如何 go 不再构造此方法。 Any advice appreciated thank you!
任何建议表示赞赏谢谢!
It should be它应该是
sum += items[i].massKg;
Your function doesnt appear to operate on any class properties so could exist entirely outside of your class.您的 function 似乎无法在任何 class 属性上运行,因此可能完全存在于您的 class 之外。 I would suggest using
reduce
to simplify this method further我建议使用
reduce
来进一步简化此方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.