7

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.

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

It's also not what arrays, lists and the like are for. If there are different kinds of elements, you probably should be using an object, giving names to the different collections.
TypeScript definitely has some support for non-homogenous types in arrays: github.com/Microsoft/TypeScript/blob/master/doc/…
@rakslice Tuples need not be homogenous. But then tuples are not arrays.
@rakslice TypeScript uses JavaScript as a thin compilation target; in this case that means that tuples use JavaScript arrays as the implementation. However, TypeScript types and static type verification, live outside of the JavaScript runtime which is otherwise 'typeless'.
@rakslice They are distinct in TypeScript's type system. If the [external] array is not of a (small) fixed size then it does not represent a tuple and the transformation would be to a suitable Array<c'> - it may also be required to perform runtime logic/checks to ensure the array is 'correctly populated' per special rules.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.