Looking for a solution similar to TypeScript extract union type from tuple, this question delves into how to split ['a' | 'b', number]
into ['a', number] | ['b', number]
rather than focusing on why they are not directly assignable.
An example scenario is illustrated with the following code snippet:
// The return type of this function needs to be adjusted, allowing F and S to be inferred without explicit definitions at function call
function treatAsConstants<
F,
S,
T extends [F, S][] = [F, S][]
>(array: T): (readonly [F, T[number][1]])[] {
return array;
}
const array = treatAsConstants<'a' | 'b', number>([['a', 1], ['b', 2]]);
// Desired outcome: (readonly ['a', number] | readonly ['b', number])[]
// Actual result: (readonly ['a' | 'b', number])[]
type A = typeof array;
In a subsequent function that utilizes array
, it becomes necessary to extract both ['a', number]
and ['b', number]
in order to shape an object. However, the current union type ['a' | 'b', number]
does not fit either description.
The attempt made to split the unions only reproduces the original input:
type SplitUnions<
TKey extends string,
TVal,
O extends { [K in TKey]: [K, TVal] } = { [K in TKey]: [K, TVal] }
> = [O[TKey][0], O[TKey][1]];
type Split = SplitUnions<'a' | 'b', number>;