如何从打字稿中带标签的联合类型中提取类型? [英] How to extract a type from a tagged union type in typescript?
本文介绍了如何从打字稿中带标签的联合类型中提取类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说已经定义了一个类型:
Say there is already a type defined as this:
export type Item = {
type: 'text',
content: string
} | {
type: 'link',
url: string
}
是否可以从类型Item
中提取link
部分?我的意思是,是否可以定义类型ExtractTypeFrom
:
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'>
LinkItem
将是:
{
type: 'link',
url: string
}
推荐答案
是的,您可能非常亲密,可以使用预定义的Extract
条件类型.您可能需要传入一个类型作为第二个参数,该类型可以是您要寻找的类型的基本类型:
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; }
这篇关于如何从打字稿中带标签的联合类型中提取类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文