Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed array length with an optional item

Tags:

typescript

I have an interface defined in my app:

interface someInterface {
    one: string;
    two: string;
}

One of my function parameters should always accept a homogeneous array of 1 or 2 elements, something like this:

// second item should be optional
[{ one: 'anyString', two: 'anyString' }, { one: 'anotherString', two: 'anotherString' }] 

I would expect that one of these types assigned to the parameter would work:

1. [someInterface, someInterface | null]
2. [someInterface, someInterface | undefined]
3. [someInterface, someInterface?]
4. someInterface[]

But 1 and 2 expect the seconds item, at least in the form of null or undefined. 3 is not a valid typescript code. 4 accepts unlimited amount of values.

Question: How to define a type of array, which accepts 1 or 2 homogeneous values: in this case, the first value should always be of someInterface type and should always be present. The second optional value, if present, should also be of type someInterface.

Basically, I am looking for a shortcut of this (i.e. in case the array should accept from 1 to 5 values):

[someInterface, someInterface] | [someInterface]
like image 576
Eduard Avatar asked Oct 26 '25 23:10

Eduard


1 Answers

You can define the type as "either a tuple with one value or a tuple with two values", which will produce an array which can be used just like a regular array:

var SomeType = [someInterface] | [someInterface, someInterface];
like image 132
Sami Kuhmonen Avatar answered Oct 28 '25 16:10

Sami Kuhmonen



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!