Home > database >  Typescript anonymous array as function parameter
Typescript anonymous array as function parameter

Time:01-17

I'm getting this error in Typescript 4.9. I understand why I'm getting the error but I'm not sure how to get around it. I've looked at nullish coalescing but that gives more errors. The parameter will always be a two-dimensional array with one or more sets of data.

private CreatePlots(data: [] ) {
    let valData = data[0][0];
    let plotInfo = <EpmsPlotQueryData>data[0][1];
    GUI.setPopupMsg("Loading query data "   this._processResults   " of "   this._PlotQueryList.length);
    plotInfo.createPlots(valData);
}

The error I'm getting for both references to data; enter image description here

enter image description here

I can change the function to have data defined as any to get past the errors i.e.

private CreatePlots(data)

but I would like to understand why I can't use an empty array like you can in javascript.

CodePudding user response:

If you know the exact type of the parameter, you should declare it like this:

data: EpmsPlotQueryData[][] or data: Array<EpmsPlotQueryData[]> or data: Array<Array<EpmsPlotQueryData>> (all 3 are the same).

private CreatePlots(data: EpmsPlotQueryData[][]) {
    let valData = data[0][0];
    let plotInfo = data[0][1];
    GUI.setPopupMsg("Loading query data "   this._processResults   " of "   this._PlotQueryList.length);
    plotInfo.createPlots(valData);
}

As for why you get the error:

  • data: any[] this is an array of anything
  • data: [number, string] this is a tuple, you are telling the compiler that data[0] is always number, data[1]`` is always string, and data[2] doesn't exist.
  • data: [] this is an empty tuple, you're telling the compiler that you'll get an empty tuple (an array which is always empty).
  • Related