Reputation: 1322
In the following example, I'm expecting the length of the array passed to the method test
to match.
Can anyone explain why it doesn't work as expected?
class Beef
{
public id: number;
}
class Steak
{
public run()
{
const testBeefs = this.getBeef();
console.log('Should be 5, got '+ testBeefs.length);
const result = this.test(testBeefs);
return result;
}
private getBeef():Beef[]
{
const output: Beef[] = [];
for (var i = 1; i <= 5; i++)
{
const newBeef = new Beef();
newBeef.id = i;
output.push(newBeef);
}
return output;
}
private test(...beefs: Beef[]): number
{
console.log('Should be 5, got '+ beefs.length);
var output = 0;
for (var i = 0; i < beefs.length; i++)
output += beefs[i].id;
return output;
}
}
According to the compiler it seems that test
is expecting and instance of Beef
, not Beef[]
. Is there a simpler way?
Example here
To explain my code, calling run will:
getBeef
with 5 instances of the class Beef
called testBeefs
testBeefs
to the method test
test
will sum the id
field of each Beef
instanceUpvotes: 0
Views: 44
Reputation: 9354
test
is not expecting an array, it is expecting an unspecified number of arguments of the type Beef
.
Either call it like:
const result = this.test(...testBeefs)
Or change the signature to simply use an array for the first argument:
private test(beefs: Beef[]): number
Upvotes: 1