Krushnasinh Jadeja
Krushnasinh Jadeja

Reputation: 624

Typescript interface property want to change optional to required depending on other property

I have the following Typescript interface:

type animation = "Grow" | "Fade" | "Slide";

interface ISnackbarProps {
  open: boolean;
  autoHideDuration?: number;
  position?: position;
  variant?: variant;
  type?: AlertColor;
  animation?: animation;
  icon?: React.ReactElement;
  slideDirection?: slideDirection;
  action?: React.ReactElement;
  handleClose: () => void;
}

In the above interface, slideDirection is optional. But I want to update it optional to required only when the animation property has the "slide" value.

Upvotes: 2

Views: 106

Answers (1)

akds
akds

Reputation: 681

You can achieve it with type. Here's an example:

type animation = "Grow" | "Fade";

type commonSnackBarProps = {
  open: boolean;
  autoHideDuration?: number;
  position?: position;
  variant?: variant;
  type?: AlertColor;
  icon?: React.ReactElement;
  action?: React.ReactElement;
  handleClose: () => void;
};

type SnackbarProps =
  | (commonSnackBarProps & {
      animation?: animation;
      slideDirection?: slideDirection;
    })
  | (commonSnackBarProps & {
      animation?: "Slide";
      slideDirection: slideDirection;
    });

You can check how this works in this sandbox.

Upvotes: 1

Related Questions