问题
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