Within my application, I have an interface that is defined as follows:
interface someInterface {
one: string;
two: string;
}
I need to create a function parameter that will always accept an array containing 1 or 2 elements of the same type. The array should look something like this:
// the second item is optional
[{ one: 'anyString', two: 'anyString' }, { one: 'anotherString', two: 'anotherString' }]
I have tried several options for assigning types to this parameter, such as:
1. [someInterface, someInterface | null]
2. [someInterface, someInterface | undefined]
3. [someInterface, someInterface?]
4. someInterface[]
However, options 1 and 2 require the second item to be either null
or undefined
. Option 3 is not valid TypeScript code. Option 4 allows for any number of values.
My Question: How can I define a type for an array that only accepts 1 or 2 homogeneous values? Specifically, the first value must always be of type someInterface
and must always be present. If there is a second value, it should also be of type someInterface
.
In essence, I am looking for a shorthand way to express the following (for cases where the array may contain 1 to 5 values):
[someInterface, someInterface] | [someInterface]