Exploring Typescript typings has led me to ponder how to create a type that is a tuple with unordered element types.
For example:
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 concept can be quite beneficial, but what if order doesn't matter or needs to be unordered?
The straightforward solution I came up with is:
type SimpleUnorderedTuple = [number, string] | [string, number];
const tup1: SimpleUnorderedTuple = [7, `7`]; // Valid
const tup2: SimpleUnorderedTuple = [`7`, 7]; // Valid
However, when dealing with numerous types, creating combinations becomes burdensome:
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 ...
Attempting to simplify this process, I aim to achieve something like:
type ABunchOfTypes = 'these' | 'are' | 'some';
type UnorderedTuple<T> = ; //...
type ComplexUnorderedTuple = UnorderedTuple<ABunchOfTypes>;
I came across an article that mentioned:
Any subsequent value we add to the tuple variable can be any of the predefined tuple types in no particular order.
However, my attempts to replicate this have proven challenging. When defining a tuple with two elements, accessing positions beyond the tuple length is restricted.