0

I have 2 pairs of nonrelated props: I want to prevent passing heading and customHeading at the same time, same with the children and copy props. However, you can pass heading and copy or heading and children because these props are nonrelated.

Having 2 pairs of nonrelated props is forcing me to create 4 conditions. If I imagine there would be more pair props it will get too complicated to write all combinations.

heading: string; or customHeading: ReactNode;

children: ReactNode; or copy: string;

Is there a better/shorter solution for conditional types?

type CommonAProps = {
  // common props
};

type ConditionalAProps =
  | {
      heading: string;
      children: ReactNode;
      customHeading?: never;
      copy?: never;
    }
  | {
      customHeading: ReactNode;
      copy: string;
      heading?: never;
      children?: never;
    }
  | {
      customHeading: ReactNode;
      children: ReactNode;
      heading?: never;
      copy?: never;
    }
  | {
      heading: string;
      copy: string;
      customHeading?: never;
      children?: never;
    }
;

type AProps = CommonAProps & ConditionalAProps;

const A = ({ heading, customHeading, children, copy }: AProps) => {
  return (
    <>
      {heading || customHeading}
      {children || copy}
    </>
  );
};
Piotr
  • 114
  • 1
  • 6
  • 2
    This might give you some pointers: https://stackoverflow.com/questions/42123407/does-typescript-support-mutually-exclusive-types – kelsny Sep 05 '22 at 13:52

0 Answers0