简体   繁体   中英

React Typescript Union type

I've created a Card component which has two variants: Wrapper and Dashboard. Each variant will have different props

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;

Now when I try use Props as the type in my component, I get:

Property 'primaryText' does not exist on type 'Props'
Property 'secondaryText' does not exist on type 'Props'
etc..

The only key which looks fine is variant which I guess is because it's the only common key in both types.

Card.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;
  }
};

What would be the best way to do this?

You already have a discriminated union type for the props. So what about this?

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;
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM