Reaching the boundary of expressibility in TypeScript is where I find myself with this scenario.
To address your point, there isn't a specific type type GoodArray = ⋯
in TypeScript that corresponds to what you are describing.
While TypeScript does have tuple types that can represent arrays with elements at specific numeric indexes, it doesn't cater to scenarios where the exact order of elements is not crucial, just as long as they all exist within the array. Consequently, achieving this would mean creating an infinite union of tuple types that fit your criteria... something like
Your custom code here...
TypeScript does not support infinite unions, so having a huge union or limiting the maximum array length might be potential workarounds, yet neither option is ideal.
An alternative approach would involve employing a generic type as a constraint rather than a fixed type. This way, T extends GoodArray<T>
would indicate that T
is valid.
This method would require implementing a generic helper function, say goodArray()
, that validates the input argument's type. So instead of directly specifying
const arr: GoodArray<⋯> = [⋯];
and manually defining the
T
type argument, you could use
const arr = goodArray([⋯]);
for simplicity.
However, even this process has its complexities. The generic type has to determine any missing element types and enforce their inclusion, perhaps utilizing recursive conditional types alongside variadic tuple types for parsing the input, as depicted below:
Here goes your additional custom code...
Testing this solution reveals success under certain inputs but underscores the intricate nature of the entire process.
In conclusion, relying solely on TypeScript's type system for such stringent requirements is challenging due to various limitations. While available methodologies offer insights into handling complex array validations, full assurance of constraint adherence remains elusive.
Link to Playground for Code Testing