I am just digging into Typescript typings and I wondered how to define a type which is a tuple but with unordered element types.
I mean, having
type SimpleTuple = [number, string];
const tup1: SimpleTuple = [7, `7`]; // Valid
const tup2: SimpleTuple = [`7`, 7]; // 'string' is not assignable to 'number'
// and vice-versa
This is useful in many cases, but what if I don't care about order or I need it to be unordered.
The example above is quite trivial since I could define
type SimpleUnorderedTuple = [number, string] | [string, number];
const tup1: SimpleUnorderedTuple = [7, `7`]; // Valid
const tup2: SimpleUnorderedTuple = [`7`, 7]; // Valid
However, I may have a bunch of types... A combinatory logic uppon them would be painful
type ABunchOfTypes = 'these' | 'are' | 'some' | 'words' | 'just' | 'for' | 'the' | 'example';
type ComplexUnorderedTuple =
['these', 'are', 'some', 'words', 'just', 'for', 'the', 'example'] |
['these', 'are', 'some', 'words', 'just', 'for', 'example', 'the'] |
// and so on ...
This is insane. There are !n
possible combinations, where n
is the number of elements (I guess, I am not too good at maths!).
I am trying to achieve something like
type ABunchOfTypes = 'these' | 'are' | 'some';
type UnorderedTuple<T> = ; //...
type ComplexUnorderedTuple = UnorderedTuple<ABunchOfTypes>;
I found in this article
Any subsequent value we add to the tuple variable can be any of the predefined tuple types in no particular order.
But I couldn't reproduce. If I define a tuple of two elements, I am not allowed to access to the nth position, if n
is greater than (or equal) the tuple length.