atconway atconway - 2 months ago 15
TypeScript Question

Load colection of elements into a Tuple in Typescript

I have a

Tuple
and am trying to use it to load a simple list of data values that are strongly typed in
TypeScript
. However I must be using incorrectly because I can't get the syntax correct for trying to add multiple sets of strongly typed elements. For example I have the following definition:

let sOptions: [number, string];
sOptions = [1, "Female"],[2, "Male"];


I've also tried making the
Tuple
an array but that didn't work either; it doesn't build and says the signature doesn't match:

let sOptions: [number, string][];


Is it possible to load multiple sets of data (1...n) in a tuple based on the tuple's definition of
[number,string]
, or am I using this type incorrectly and there would be a more preferred way?

Answer

You need to actually wrap sOptions in square brackets:

let sOptions: [number, string][];
sOptions = [ [1, "Female"], [2, "Male"] ];

Otherwise, the comma operator a,b in TypeScript simply evalutes to the second operand, b. That's why you're getting a signature mismatch.