Load a union of elements into a tuple in Typescript

I have Tupleand am trying to use it to load a simple list of data values ​​that are strongly typed into TypeScript. However, I have to use it incorrectly because I cannot get the syntax correctly to try to add several sets of strongly typed elements. For example, I have the following definition:

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

I also tried to make an array Tuple, but that didn't work either; he does not build and says that the signature does not match:

let sOptions: [number, string][];

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

+4
source share
2 answers

You need to actually wrap sOptionsin square brackets:

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

Otherwise, the comma operator a,b in TypeScript simply evaluates the second operand b. That is why you get signature mismatch.

+1
source

A type [number, string]is a type of a size-2 array that you might consider a tuple. Let me call this type YourTuple.

Since you want to sOptionscontain a bunch of them, it must be of type Array<YourTuple>(also written YourTuple[]).

Then, to write many of them to the sOptions array, you need to use the correct array syntax, with the addition of additional [ ... ], for example:

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

, TypeScript , , , , 2.

- , , , :

interface NumberAndGender {
  number: number;
  gender: string;
}
+1

Source: https://habr.com/ru/post/1656039/


All Articles