【问题标题】:Separate each member of a union type分隔联合类型的每个成员
【发布时间】:2019-01-01 01:00:58
【问题描述】:

我有一个生成的联合类型,看起来像:

type Result = { type: 'car' } | { type: 'boat' }

我怎样才能将它们分开,以便我可以为它们中的每一个创建一个单独的类型?例如:

type BoatResult = { type: 'boat' }
type CarResult = { type: 'card' }

必须从原始 Result 类型创建它们。

【问题讨论】:

    标签: typescript discriminated-union


    【解决方案1】:

    您可以使用Extract 条件类型到Extract 从扩展给定类型的联合中获取类型。如果您的联合实际上像问题中那样简单,那没有多大意义,但如果您有额外的字段,您可以使用它从联合中提取完整类型。

    type Result = { type: 'car', a: number } | { type: 'boat', b: string }
    
    type Car = Extract<Result, { type: 'car' }> //{ type: 'car', a: number }
    type Boat = Extract<Result, { type: 'boat'} > // { type: 'boat', b: string }
    

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      相关资源
      最近更新 更多