How to extract a type from a tagged union type in typescript?

醉酒当歌 提交于 2020-06-27 07:36:19

问题


Say there is already a type defined as this:

export type Item = {
  type: 'text',
  content: string
} | {
  type: 'link',
  url: string
}

Is it possible to extract the link part from the type Item? I mean, is it possible to define a type ExtractTypeFrom:

type LinkItem = ExtractType<Item, 'type', 'link'>

And the LinkItem will be:

{
  type: 'link',
  url: string
}

回答1:


Yes it is possible you are very close, you can use the predefined Extract conditional type. You can will need to pass in, as the second argument, a type that can be a base type for the type you are seeking:

type LinkItem = Extract<Item, { type: 'link' }> // will be  { type: "link"; url: string; }


来源:https://stackoverflow.com/questions/52943105/how-to-extract-a-type-from-a-tagged-union-type-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!