2

I'm trying to pass this TypeScript array to a function. I've tried a number of parameter types to make this compile, but none of them seem to work. Here's the array:

var driverTally = [
                    { driver: 'driver1', numEscorts: 0},
                    { driver: 'driver2', numEscorts: 0},
                    { driver: 'driver3', numEscorts: 0} 
                ];

doStuff(driverTally : Array<[string,number]>){ ... }

The compiler keeps saying : "Argument of type '{ driver: string; numEscorts: number; }[]' is not assignable to parameter of type '[string, number][]'.

2 Answers 2

3

You cna use any if you are not sure about the type,

doStuff(driverTally : any){ ... }

or create a Class of the following type

export class Driver {
   public string driver;
   public int numEscorts;
}

and then declare your array as,

driverstally : Driver[] = [
                    { driver: 'driver1', numEscorts: 0},
                    { driver: 'driver2', numEscorts: 0},
                    { driver: 'driver3', numEscorts: 0} 
                ];

and then pass it as,

doStuff(driverTally :Driver[] ){ ... }
Sign up to request clarification or add additional context in comments.

1 Comment

I made a Driver class. I guess I should have just done that right away, but it bugged me that I couldn't get the type right for the function. Thanks.
0

I recommend you to determine interface:

interface IDriver {
    drive: string;
    numEscorts: number;
}

Then declare array with initialization:

public drivers: IDriver[] = [];

After you can pass this array as function parameter:

doStuff(driverTally: IDriver[] ){ ... }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.