javascriptmaterial-uireact-proptypes

How can I do a boolean | undefined vs boolean | null PropType?


I have:

const propTypes = {
  ... // some other stuff
  disableEscapeKeyDown: PropTypes.bool,
};
export type ModalProps = PropTypes.InferProps<typeof propTypes>;

export default function ModalWindow({
  ...// other stuff
  disableEscapeKeyDown = false,
}: ModalProps) {
  const classes = useStyles({ width });
  return (
    <Modal
      open={open ?? false}
      onClose={onClose}
      disableEscapeKeyDown={disableEscapeKeyDown}
    >

But that gives me an error: Type 'boolean | null' is not assignable to type 'boolean | undefined'.

It seems that a MUI Modal takes boolean | undefined whereas the PropType has it has boolean | null. How can I reconcile that?


Solution

  • Option 1: Check for null:

        <Modal
          open={open ?? false}
          onClose={onClose}
          disableEscapeKeyDown={disableEscapeKeyDown === null ? undefined : disableEscapeKeyDown}
        >
    

    or you can also use ??:

    disableEscapeKeyDown ?? undefined
    

    Option 2: Omit & intersect with correct type:

    export default function ModalWindow({
      disableEscapeKeyDown = false,
    }: Omit<ModalProps, "disableEscapeKeyDown"> & { disableEscapeKeyDown?: boolean }) {
    

    Option 3: Change the definition of ModalProps:

    type ModalProps = PropTypes.InferProps<Omit<typeof propTypes, "disableEscapeKeyDown">> & { disableEscapeKeyDown?: boolean };
    

    Option 4: Ignore TypeScript:

        <Modal
          open={open ?? false}
          onClose={onClose}
          //@ts-ignore
          disableEscapeKeyDown={disableEscapeKeyDown}
        >
    

    Unfortunately, I don't think you can "overwrite" or change how PropTypes.InferProps works - even trying to redefine Requireable<T> and Validator<T> did not work (at least my attempts to do it). So here's the next best thing: patching the results of the type yourself.

    Playground with all the options