我正在尝试将此TypeScript数组传递给函数。我已经尝试了许多参数类型来进行编译,但它们似乎都不起作用。这是阵列:
var driverTally = [
{ driver: 'driver1', numEscorts: 0},
{ driver: 'driver2', numEscorts: 0},
{ driver: 'driver3', numEscorts: 0}
];
doStuff(driverTally : Array<[string,number]>){ ... }
编译器一直说:“类型'{driver:string; numEscorts:number;} []'的参数不能分配给'[string,number] []'类型的参数。
答案 0 :(得分:2)
如果你不确定类型,你可以使用任何一种,
doStuff(driverTally : any){ ... }
或创建以下类型的类
export class Driver {
public string driver;
public int numEscorts;
}
然后将您的数组声明为
driverstally : Driver[] = [
{ driver: 'driver1', numEscorts: 0},
{ driver: 'driver2', numEscorts: 0},
{ driver: 'driver3', numEscorts: 0}
];
然后传递给它,
doStuff(driverTally :Driver[] ){ ... }
答案 1 :(得分:0)
我建议您确定界面:
interface IDriver {
drive: string;
numEscorts: number;
}
然后使用初始化声明数组:
public drivers: IDriver[] = [];
您可以将此数组作为函数参数传递:
doStuff(driverTally: IDriver[] ){ ... }