【发布时间】:2023-03-30 11:10:02
【问题描述】:
当props.group为true时,我想将tab对象的类型推断为{leftText: string, rightText?: string}类型,当props.group为false时推断{title: string}类型。
type ButtonTab =
| {
leftText: string;
rightText?: string;
}
| { title: string };
interface ButtonTabsProps {
tabsList: ButtonTab[];
group?: boolean;
}
function ButtonTabs(props: Readonly<ButtonTabsProps>) {
return props.tabsList.map((tab: ButtonTab) => {
if(props.group) {
return `${tab.leftText} ${tab.rightText}`
}
return `${tab.title}`
})
}
目前,TSC 抛出错误:
类型“ButtonTab”上不存在属性“leftText”。 类型 '{ title: string; 上不存在属性 'leftText' }'。
【问题讨论】:
-
听起来您希望
ButtonTabsProps成为联合类型,而不是ButtonTab。
标签: typescript typescript-typings