typescript条件类型应该如何上手

比如如下类型

type ShowComponent = {
    text?: string;
    urlId?: string;
    component: 'Text' | 'Image';
}

我希望当component为Text时 text为必选,为Image时urlId为必选
应该如何定义该类型?

熟练上手ts类型,有哪些代码仓库或者书籍推荐呢?谢谢!

阅读 1.5k
2 个回答
type ShowComponent = {
    text: string;
    component: 'Text';
} | {
    urlId: string;
    component: 'Image';
}
推荐问题