0
votes

Can I define mixed types of array content in Typescript?

I am returning some results in the format of a 2d array like:

[
  [ 'red', 0.1 ],
  [ 'blue', 0.2 ]
]

I would like to define some type of inner structure which is the two element array like

interface Match {
  [string, number]
}

then my later functions could return Promise<Match[]>

But not sure how of the syntax to do this.

Even if I just try the simplest syntax, I don't know how to define an array which mixes two items,

string[][]

would be find for a 2d array of strings, but since this is more like a tuple, mixing types inside the array...

I guess I could give up and use a clearer labeled type like

interface Match {
  tag: string
  conf: number
}

but that seems it would be inefficient creating objects, since I will have a TON of these data instances (internal machine learning data structure)

Thoughts?

I found a page on tuples in typescript but not clear how to export an Interface using them.

https://www.tutorialsteacher.com/typescript/typescript-tuple

1

1 Answers

1
votes

Instead of using an interface, just use a type alias, which was designed for this purpose:

type Match = [string, number];

Your array type would then be Match[]. Without the type alias, it'd just be [string, number][].