[英]Split tuple of unions into union of tuples in TypeScript
这个问题类似于TypeScript extract union type from tuple ,但不是问为什么一个不能分配给另一个(我理解那个位),我想知道如何制作 function 或 type split ['a' | 'b', number]
['a' | 'b', number]
变成['a', number] | ['b', number]
['a', number] | ['b', number]
。
假设我有这个人为的代码:
// 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;
在后面的array
中,我需要Extract
['a', number]
和['b', number]
以确定 object 的形状。 然而, ['a' | 'b', number]
['a' | 'b', number]
不适合这两种类型。
这是我分裂工会的最佳尝试,但它只是给了我我一开始的样子。
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>;
我非常接近。 而不是[O[TKey][0], O[TKey][1]]
我只需要O[TKey]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.