【发布时间】:2021-08-05 10:27:34
【问题描述】:
我创建了一个 Card 组件,它有两个变体:Wrapper 和 Dashboard。每个变体都会有不同的道具
export type DashboardProps = {
variant: CardVariant.Dashboard,
primaryText: string,
secondaryText: string,
icon: OverridableComponent<SvgIconTypeMap<{}, "svg">>,
iconColor: string,
}
export type WrapperProps = {
variant: CardVariant.Wrapper,
children: any,
}
export type Props = DashboardProps | WrapperProps;
现在,当我尝试在组件中使用 Props 作为类型时,我得到:
Property 'primaryText' does not exist on type 'Props'
Property 'secondaryText' does not exist on type 'Props'
etc..
唯一看起来不错的键是 variant,我猜这是因为它是两种类型中唯一的通用键。
卡片.tsx
export const Card = ({
variant,
primaryText,
secondaryText,
icon,
iconColor,
children,
}: Props) => {
switch (variant) {
case CardVariant.Wrapper:
return <CardWrapper>{children}</CardWrapper>;
case CardVariant.Dashboard:
return (
<CardDashboard
primaryText={primaryText}
secondaryText={secondaryText}
icon={icon}
iconColor={iconColor}
/>
);
default:
return null;
}
};
最好的方法是什么?
【问题讨论】:
-
使用某种type narrowing。
标签: reactjs typescript