Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load collection 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?

like image 283
atconway Avatar asked Sep 28 '16 03:09

atconway


2 Answers

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.

like image 182
Frxstrem Avatar answered Nov 15 '22 08:11

Frxstrem


The type [number, string] is the type of a size-2 array, which for your concerns you might consider a tuple. Let's call this type YourTuple.

Since you want sOptions to contain a bunch of those, it needs to have type Array<YourTuple> (also written YourTuple[]).

Then to write many of them into the sOptions array, you need to use the proper array syntax, with an additional [ ... ] enclosing it, like this:

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

By the way, the support for fixed-sized array in TypeScript has been a bit bad but is getting better, so sometimes you might still get issues where it loses track of the fact that your tuples have size 2.

If this is for something more complicated, you might want to consider turning your tuples into objects with fields indicating what the components mean:

interface NumberAndGender {
  number: number;
  gender: string;
}
like image 38
Ptival Avatar answered Nov 15 '22 10:11

Ptival