0

I'm currently making an abstracted component for a modal. It can have one, two, or three call to actions (buttons, links, etc.)

The modal will have role="alertdialog", meaning I should identify the safest item to initially focus on for accessibility purposes. The modal conditionally renders typical "X" close button in the upper-right corner.

I'm using overloading to get as far as I have gotten, but I'd only like 'xButton' to be in the union type option if "withCloseButton" is true. Is this possible without generics? If it requires generics, is there a way to do an inference generic?

type ForwardRefRenderFn = React.ForwardRefRenderFunction<any, { [key: string]: any }>;

type CTAItem = CTAModalButton | ForwardRefRenderFn;

type OneCTA = {
  primaryCTA: CTAItem;
  secondaryCTA: undefined;
  tertiaryCTA: undefined;
  leastDestructiveElement: 'primaryCTA' | 'xButton';
};

type TwoCTAs = {
  primaryCTA: CTAItem;
  secondaryCTA: CTAItem;
  tertiaryCTA: undefined;
  leastDestructiveElement: 'primaryCTA' | 'secondaryCTA' | 'xButton';
};

type ThreeCTAs = {
  primaryCTA: CTAItem;
  secondaryCTA: CTAItem;
  tertiaryCTA: CTAItem;
  leastDestructiveElement: 'primaryCTA' | 'secondaryCTA' | 'tertiaryCTA' | 'xButton';
};

export type TransactionModalProps = ModalProps & (OneCTA | TwoCTAs | ThreeCTAs) &
  { withCloseButton?: boolean }; 

1 Answer 1

1

I'm not entirely sure what you want, but something like this might help:

type OneCTA<T> = {
  primaryCTA: CTAItem;
  secondaryCTA: undefined;
  tertiaryCTA: undefined;
  leastDestructiveElement: 'primaryCTA' | T;
};

type TransactionModalProps<T> = T extends { withCloseButton: true }
  ? OneCTA<'xButton'> | TwoCTAs<'xButton'> | ThreeCTAs<'xButton'>
  : OneCTA<unknown> | TwoCTAs<unknown> | ThreeCTAs<unknown>;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.