How can I alter the types for material UI alert component?

Viewed 2101

I am relatively new to Typescript and I have created a snackbar component using React Context and when I try to set the Alert severity, I get this error "Type 'string' is not assignable to type 'Color | undefined'." I do have the type set to a string however, I cannot seem to figure out how to give it a type of Color. Here is my Alert component:

const AppAlert = () => {
  const alertContext = useContext(AlertContext);

  return (
    <div>
      <Snackbar open={alertContext.snackbarOpen}>
        <Alert severity={alertContext.snackbarType} variant="filled">
          {alertContext.snackbarMessage}
        </Alert>
      </Snackbar>
    </div>
  );
};

export default AppAlert;

Here are my Alert prop types:

interface AlertProps {
  snackbarOpen: boolean;
  snackbarType: string;
  snackbarMessage: string;
  setAlert: (type: string, message: string) => void;
}

I hope I was specific enough as I am still working on understanding TS.

2 Answers

The severity of Material-ui alerts can be one of four types 'error' | 'info' | 'success' | 'warning' according to the documentation material-ui.com/api/alert. The problem you are having is because the severity property of your Alert component has been assigned an undefined value from your alertContext.snackbarType. To avoid errors if something goes wrong, it would be good practice to set a default severity type as follows:

<Alert severity={alertContext?.snackbarType || 'warning'} variant="filled">
    {alertContext?.snackbarMessage}
</Alert>

I just ran into the same issue and solved it by importing the type from @material-ui/lab/Alert:

import React from 'react';
import Alert from '@material-ui/lab/Alert';
import type { Color } from '@material-ui/lab/Alert'

interface Props{
    severity: Color,
    message: string
}

export const BuildReportAlert = (props: Props) => {

    const {severity, message} = props;

    return (
        <Alert
            variant='outlined'
            severity={severity}
        >
            {message}
        </Alert>
    )

}
Related