TS 错误 - 创建自定义 React 警报组件

TS Error - Create Custom React Alert Component

我正在尝试创建一个自定义的 React material ui 警报组件,我可以通过简单地将文本和严重性作为参数传递到不同的页面上来调用它。我正在尝试使用这个:

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

但我一直在第一个严重性词 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'

我该如何解决这个问题?或者是否有其他方法来自定义此组件?

编辑:我仍然无法在我的其他页面中使用它:

  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>
              )
        }       
      }}
  }

我在 CustomAlert 上收到以下错误:

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)

Alert只能接受有限数量的字符串或未定义,所以你必须明确你的通行证字符串是这种类型。

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

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

现在,TS 编译器知道 severity 将是联合类型之一 Severity,不应抛出错误。

我遇到了类似的问题。我使用来自 '@mui/material/Alert'

的 AlertColor 类型修复了它
import MuiAlert, { AlertProps, AlertColor } from '@mui/material/Alert';

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