简体   繁体   中英

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.

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 .

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