简体   繁体   English

将联合元组拆分为 TypeScript 中的元组联合

[英]Split tuple of unions into union of tuples in TypeScript

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]这个问题类似于TypeScript extract union type from tuple ,但不是问为什么一个不能分配给另一个(我理解那个位),我想知道如何制作 function 或 type split ['a' | 'b', number] ['a' | 'b', number] into ['a', number] | ['b', number] ['a' | 'b', number]变成['a', number] | ['b', number] ['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.在后面的array中,我需要Extract ['a', number]['b', number]以确定 object 的形状。 However, ['a' | 'b', number]然而, ['a' | 'b', number] ['a' | 'b', number] fits neither of those types. ['a' | 'b', number]不适合这两种类型。

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] .而不是[O[TKey][0], O[TKey][1]]我只需要O[TKey]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM