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?
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With