Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an Array of Tuples in Typescript

It's easy to create a generic pair type ( simplest possible Tuple ) i.e.

type Pair<A, B> = [A, B]

The question is how to create an type which represents and array of such generic pairs.

The only requirement is for element in the array to be a pair. The type of the first element and the type of the second element ought to be polymorphic, any does not make the cut, otherwise this would be satisfactory:

type Pair = [any, any]
type Pairs = Pair[]
like image 337
Mateja Petrovic Avatar asked May 02 '19 00:05

Mateja Petrovic


2 Answers

Pair<T, K> is the same as [T, K] yes, it will do what you want but its syntactically unnecessary.

To create an array of tuples it just would be Array<[TYPE, TYPE]> or [TYPE, TYPE][]

like image 71
Shanon Jackson Avatar answered Oct 21 '22 08:10

Shanon Jackson


I feel like I am missing a nuance here.. But believe this is what you are asking for:

type Pair<T,K> = [T,K];
type Pairs<T,K> = Pair<T,K>[];

  const apple: Pair<number,number> = [2,3];
  const orange: Pair<number,number> = [3,4];
  const food: Pairs<number, number> = [apple, orange];
like image 30
ttugates Avatar answered Oct 21 '22 06:10

ttugates