You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typescript 如何为 React Alert 组件的 severity 属性添加类型声明?

解决方案

你遇到的是MUI Alert组件severity属性的类型不匹配问题,不需要使用any,可以直接使用MUI内置的官方类型,有两种实现方案:

  • 方案1:直接使用MUI内置导出的类型(推荐,后续MUI版本更新可自动同步类型)
    首先从Alert组件的类型定义中提取severity的类型:
    // 先导入Alert的类型定义
    import type { AlertProps } from '@mui/material/Alert'
    
    type ticketData = {
      name: string;
      title: string;
      onClose: () => void;
      message: string[];
      // 直接复用内置的severity类型
      severity: AlertProps['severity'];
    }
    
  • 方案2:手动写对应的联合类型,severity的合法值只有四个固定可选值,类型定义如下:
    type ticketData = {
      name: string;
      title: string;
      onClose: () => void;
      message: string[];
      severity: 'success' | 'info' | 'warning' | 'error' | undefined;
    }
    

类型报错的原因是你之前给severity定义的类型范围太宽(比如定义为string类型),不符合MUI限定的固定枚举值要求,用上面两种方式都可以完美匹配类型要求,不需要用any兜底。

内容的提问来源于stack exchange,提问作者cheesydoritosandkale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 13:36:03