This question is similar to TypeScript extract union type from tuple , but instead of asking why one isn't assignable to the other (I understand that bit), I want to know how to make a function or type split ['a' | 'b', number]
['a' | 'b', number]
into ['a', number] | ['b', number]
['a', number] | ['b', number]
.
Suppose I have this contrived code:
// the return type of this needs to change, and ideally it can infer F and S without
// specifying them the 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: (readonly ['a', number] | readonly ['b', number])[]
// actual: (readonly ['a' | 'b', number])[]
type A = typeof array;
In a later function that takes in array
, I need to Extract
['a', number]
and ['b', number]
in order to determine the shape of an object. However, ['a' | 'b', number]
['a' | 'b', number]
fits neither of those types.
Here's my best attempt at splitting the unions, but it just gives me exactly what I started with.
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>;
I was pretty close. Instead of [O[TKey][0], O[TKey][1]]
I simply needed O[TKey]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.