Fre*_*ind 13 types typescript union-types
假设已经定义了一个类型:
export type Item = {
type: 'text',
content: string
} | {
type: 'link',
url: string
}
Run Code Online (Sandbox Code Playgroud)
是否可以link从类型中提取零件Item?我的意思是,是否可以定义一个类型ExtractTypeFrom:
type LinkItem = ExtractType<Item, 'type', 'link'>
Run Code Online (Sandbox Code Playgroud)
而且LinkItem将是:
{
type: 'link',
url: string
}
Run Code Online (Sandbox Code Playgroud)
Tit*_*mir 22
是的,您可能非常接近,您可以使用预定义的Extract条件类型。您可能需要传入一个类型作为第二个参数,该类型可以是您正在寻找的类型的基类型:
type LinkItem = Extract<Item, { type: 'link' }> // will be { type: "link"; url: string; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3151 次 |
| 最近记录: |