TS Error - Create Custom React Alert Component

Viewed 1579

I am trying to create a custom react material ui alert component that I can call on different pages by simply passing in the text and severity as parameters. I am trying to use this:

export default function CustomAlert(severity: string, text: string){
    <Alert style={{width:'50%'}} severity={severity}> {text}</Alert>
}

but I keep getting an error on the first severity word severity={severity}that:

Type 'string' is not assignable to type '"error" | "success" | "info" | "warning" | undefined'.ts(2322)
Alert.d.ts(25, 3): The expected type comes from property 'severity' which is declared here on type 'IntrinsicAttributes & AlertProps'

How could I fix this? Or is there an alternative method to customise this component?

Edit: I am still not being able to use it in my other page:

  function StatusMessage(){
    if (isRemoved){
      return (
      <Alert style={{width:'25%'}} severity="success"> User Removed</Alert>
        )
      }
      else{
        if(errorMessage!=''){
        if (errorMessage.includes(`Couldn't find user`)){
          return (
            <div>
            {/* <Alert style={{width:'25%'}} severity="error"> Couldn't Find User</Alert> */}
            <CustomAlert></CustomAlert>
            </div>
              )
        }       
      }}
  }

I get errors on CustomAlert that:

JSX element type 'void' is not a constructor function for JSX elements.ts(2605)
Type '{}' is not assignable to type '(IntrinsicAttributes & "success") | (IntrinsicAttributes & "info") | (IntrinsicAttributes & "warning") | (IntrinsicAttributes & "error")'.
  Type '{}' is not assignable to type '"error"'.ts(2322)
2 Answers

The Alert can only take a finite number of strings or undefined, so you have to be explicit that your passes string is of this type.

type Severity = "error" | "success" | "info" | "warning" | undefined;

export default function CustomAlert(severity: Severity, text = "Sorry"){
    <Alert style={{width:'50%'}} severity={severity}> {text}</Alert>
}

Now, the TS compiler knows for a fact that severity will be one of the union type Severity, and shouldn't throw an error.

I had a similar problem. I fixed it using AlertColor type from '@mui/material/Alert'

import MuiAlert, { AlertProps, AlertColor } from '@mui/material/Alert';

interface INotificacao {
    texto:string,
    duracao:number,
    tipo: AlertColor /* <--- type here */
}
Related