将联合类型更改为类型数组的联合

huangapple go评论53阅读模式
英文:

Change Union type to Union of arrays of type

问题

可以创建一个辅助的泛型类型来对联合类型中的所有类型进行更改吗?

例如,这4个类型可以是一些具有许多属性的合适接口:

type A = 'a'

type B = 'b'

type C = 'c'

type D = 'd'

type unionForArr = A | B | C | D

type desired<T> = T extends A ? A[] :
                 T extends B ? B[] :
                 T extends C ? C[] :
                 T extends D ? D[] : never

type wrong = unionForArr[]

这里使用了条件类型,根据输入的类型 T 来确定返回的类型。如果 TA,则返回 A[],以此类推。

英文:

Is it possible to create a helper generic type to make changes to all types within a union?

For example these 4 types that could be some proper interfaces with lots of properties

type A = &#39;a&#39;

type B = &#39;b&#39;

type C = &#39;c&#39;

type D = &#39;d&#39;

type unionForArr = A | B | C | D

type desired&lt;unionForArr&gt; = A[] | B[] | C[] | D[]

type wrong = unionForArr[]

答案1

得分: 1

type ToArrays<T> = T extends T ? T[] : never;

type UnionForArr = 'a' | 'b' | 'c' | 'd';
type Desired = ToArrays<UnionForArr>; // 'a'[] | 'b'[] | 'c'[] | 'd'[]

TypeScript Playground

英文:
type ToArrays&lt;T&gt; = T extends T ? T[] : never;

type UnionForArr = &#39;a&#39; | &#39;b&#39; | &#39;c&#39; | &#39;d&#39;
type Desired = ToArrays&lt;UnionForArr&gt; // &#39;a&#39;[] | &#39;b&#39;[] | &#39;c&#39;[] | &#39;d&#39;[]

TypeScript Playground

huangapple
  • 本文由 发表于 2023年3月8日 17:58:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定