简体   繁体   English

在联合上分配泛型类型

[英]Distribute a generic type over a union

Is there a way in TS to "distribute" a generic type over a union? TS 中有没有办法通过联合“分发”泛型类型?

type Container<A> = { value: A };

type Containers<string | number> = Container<string> | Container<number>

(Assuming that we know from the context when to apply Containers vs Container ) (假设我们从上下文中知道何时应用ContainersContainer

surprisingly, type inference would do that for you:令人惊讶的是,类型推断会为您做到这一点:

type Container<T> = { value: T }

type Containers<T> = T extends infer A ? Container<A> : never;

the compiler is smart enough to disjoint all of them:编译器足够聪明,可以将它们全部脱节:

type C = Containers<string | number | {x: number} | {z: string} | boolean>

type C expands the following way: C型扩展如下:

type C = Container<string> | 
         Container<number> | 
         Container<false> | 
         Container<true> | 
         Container<{
           x: number;
         }> | 
         Container<{
           z: string;
         }>

ts-playground ts-游乐场

Given your sample code I think you want to define a generic type that is constrained to a union of types.鉴于您的示例代码,我认为您想要定义一个受限于类型联合的泛型类型。 One of these should fit your bill.其中之一应该适合您的账单。

type Container<T> = { value: T };
type ContainerA = Container<string | number>;
type ContainerB = Container<string> | Container<number>
type ContainerC<T extends string | number> = Container<T>;

Note also that Spread is a syntax rule in JavaScript.另请注意, Spread是 JavaScript 中的语法规则。 Its usage in your question is confusing.它在您的问题中的用法令人困惑。

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

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