【问题标题】:React Typescript Union type反应打字稿联合类型
【发布时间】: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;
  }
};

最好的方法是什么?

【问题讨论】:

标签: reactjs typescript


【解决方案1】:

您已经为道具设置了可区分的联合类型。那么这个呢?

export const Card = (props: Props) => {
  switch (props.variant) {
    case CardVariant.Wrapper:
      return <CardWrapper>{props.children}</CardWrapper>;
    case CardVariant.Dashboard:
      return (
        <CardDashboard
          primaryText={props.primaryText}
          secondaryText={props.secondaryText}
          icon={props.icon}
          iconColor={props.iconColor}
        />
      );

    default:
      return null;
  }
};

【讨论】:

  • 解决了!谢谢
猜你喜欢
  • 1970-01-01
  • 2017-05-18
  • 2018-12-06
  • 2020-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
相关资源
最近更新 更多