繁体   English   中英

大批<union of type>到数组<union of generic type></union></union>

[英]Array<Union of type>to Array<Union of generic type>

我正在尝试定义两个数组类型之间的关系,由 Wrapper 泛型类型相关:

interface WrapperType<T> {
  innerValue: T;
}

type InnerArrayType = (TypeA | TypeB | TypeC)[];
type WrappedArrayType = (WrapperType<TypeA>|WrapperType<TypeB>|WrapperType<TypeC>)[];

但是,两种联合类型之间的信息。 当其中一个更改时,另一个也必须手动更改。 我想知道是否有一个可重用的实用程序类型可以采用 InnerArrayType 和 WrapperType 和 output WrappedArrayType。

type MagicUtility<T> = ???????

type WrappedArrayType = MagicUtility<InnerArrayType>;
// equivalent to
type WrappedArrayType = (WrapperType<TypeA>|WrapperType<TypeB>|WrapperType<TypeC>)[];

在我的用例中,TypeA、TypeB、TypeC... 的列表是预定义的、static 和有限的。 请注意,它们不是字符串类型。

更新

我能够使用以下方法获得Array<Generic of union> 所以有一种方法可以将Array<Generic of union>转换为Array<Union of generic> ,问题就解决了。 但是,这似乎是一个不可能的问题: https://github.com/Microsoft/TypeScript/issues/27272

interface MyWrapper<T> {
    inner: T;
}

type ArrayOfUnionToArrayOfUnionOfGeneric<T> = 
  T extends (infer U)[]
  ? MyWrapper<U>[]
  : never;

type Inner = (1 | 2 | 3)[];
type Outer = ArrayOfUnionToArrayOfUnionOfGeneric<Inner> // MyWrapper<1 | 2 | 3>[]

// MyWrapper<1 | 2 | 3>[] --(HOW???)--> (MyWrapper<1>|MyWrapper<2>|MyWrapper<3>)[]

这可以使用分布条件类型U extends infer V部分是分布在联合上的部分。

type MagicUtility<T extends any[]> =
  (T extends (infer U)[] ? U extends infer V ? WrapperType<V> : never : never)[]

游乐场链接

暂无
暂无

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

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