Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: How can I declare a type for a JavaScript array with different element types but not a fixed length?

Tags:

typescript

Suppose I will have a JavaScript array that has a specific pattern of different element types at the start, but then a (pattern of) repeating item type(s) at the end, to an arbitrary number of repetitions.

How can I declare a TypeScript type that will be compatible with this JavaScript array?

interface A {
  foo: Foo,
  bar: Bar,
}

interface B {
  baz: Baz
}

interface Bat {
  // getArr(): [A, B, B, B],  // tuple type puts types at specific indexes 
                              // but only supports a fixed number of elements
  // getArr(): Array<A | B>,  // array type notation allows arbitrary number 
                              // of elements but doesn't require them to be
                              // in specific positions
}

Edit:

To clarify further, I am experimenting with using external TypeScript declarations with vanilla JavaScript code to identify issues in existing JavaScript code. I understand the representation may be unwise; if more wisdom had been employed in the creation of the original JavaScript code I would not have set out on this adventure.

like image 351
rakslice Avatar asked Mar 26 '16 19:03

rakslice


1 Answers

It is not possible to declare such in TypeScript's type system: arrays must have a homogenous type1

In this case the array (Array<c'>) is of a homogenous c', where c' = A | B.


Of course, if the data-structure could be decomposed, then some additional/complex encoding might be "suitable", eg.

[ A, Array<B> ]

1 I'm not aware of any programming language type system that allows such a restriction - for an unbound sequence - based on arbitrary pattern rules.

like image 104
user2864740 Avatar answered Oct 06 '22 01:10

user2864740