Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Typescript ensure arrays have a repeating type pattern? e.g. [string, number, string, number, ....(forever)]

Tags:

typescript

I have a function, which I want to ensure takes a string, followed by a number. And optionally, more string number pairs. So like a tuple, but "infinite" times:

const fn = (...args: [string, number] |
[string, number, string, number] |
[string, number, string, number, string, number] |
[string, number, string, number, string, number, string, number] | ...etc etc) => {}

and so on

An alternative psuedo type construction:

type Pair = [string, number, ...Pair];

Is this possible with TypeScript?

EDIT This looks like it should work, but doesn't. TypeScript does not seem to infer the order of the pairs correctly.

type Pair = [string, number, ...Pair[]];
like image 625
Ashley Coolman Avatar asked Dec 18 '25 09:12

Ashley Coolman


1 Answers

I believe so. You would define the type as

type RecurringTuple = [string, number, RecurringTuple[]];
const fn = (...args: RecurringTuple) => {}

Haven't tested, but found a similar case in this link.

like image 140
joshwilsonvu Avatar answered Dec 20 '25 01:12

joshwilsonvu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!