0

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 Answer 1

1

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][].

Sign up to request clarification or add additional context in comments.

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.