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.
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.
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