这个问题类似于TypeScript从元组中提取并集类型,但我不想问为什么一个不能分配给另一个(我理解这一点(,而是想知道如何使函数或类型将['a' | '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]
来确定对象的形状。然而,['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]
而不是[O[TKey][0], O[TKey][1]]
。