Given:
Tuple
: A tuple typeValues
: A type containing a union of all values that are expected to be in Tuple
Provide:
A validation type that returns Tuple
only if it contains every value in Values
(regardless of order). Otherwise, it returns never
.
type TupleOf<Tuple extends ReadonlyArray<Values>, Values> =
IsEqual<Values, TupleToUnion<Tuple>> extends true ? Tuple : never;
type abc = 'a'|'b'|'c';
function tupleOfAbc<Tuple extends ReadonlyArray<abc>>(valueOrder: TupleOf<Tuple, abc>): void {}
tupleOfAbc(['a', 'b', 'c']); // Valid
tupleOfAbc(['b', 'a', 'c']); // Valid
tupleOfAbc(['a', 'c']); // Invalid
Constructing an array that indicates the correct ordering of a known set of values:
function sort<Values, SortOrder extends ReadonlyArray<Values>>(values: Set<Values>, sortOrder: TupleOf<SortOrder, Values>) {
return [...values].sort((a, b) => sortOrder.indexOf(a) - sortOrder.indexOf(b));
}
const ABC_SORT_ORDER = ['a', 'b', 'c'] as const;
const myValues = new Set<abc>(['c', 'a']);
console.log(sort(myValues, ABC_SORT_ORDER));
The TupleOf
type allows us to ensure that the sort order is exhaustive for the type in question.
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too