zXynK
zXynK

Reputation: 1322

Using open-ended params in TS with classes

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:

  1. Create an array via getBeef with 5 instances of the class Beef called testBeefs
  2. Pass testBeefs to the method test
  3. test will sum the id field of each Beef instance

Upvotes: 0

Views: 44

Answers (1)

lawrence-witt
lawrence-witt

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

Related Questions