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

自定义Notistack组件时出现TypeScript错误,求解决

解决Notistack自定义组件添加description字段后的TypeScript类型错误

问题根源

Notistack默认的SnackbarOptions类型并未包含description字段,直接传递该参数会触发TypeScript类型校验错误,需要扩展框架内置类型来兼容自定义属性。

解决步骤

1. 扩展Notistack的类型定义

在项目中创建一个类型声明文件(如notistack.d.ts),或者直接在自定义组件文件中添加以下扩展代码:

import type { SnackbarOptions } from 'notistack';

declare module 'notistack' {
  interface SnackbarOptions {
    description?: string;
  }
}

这段代码会告知TypeScript,SnackbarOptions类型现在支持可选的description属性。

2. 保留自定义组件的正确实现

你的自定义组件代码无需修改,因为CustomContentProps会自动继承扩展后的SnackbarOptions属性:

import { type CustomContentProps, SnackbarContent } from 'notistack';
import React from 'react';
import { type AlertColor } from '@mui/material';
import { Alert } from '@mui/material';

interface NotistackVariantsProps extends CustomContentProps {
  description?: string;
}

export const NotistackVariants = React.forwardRef<HTMLDivElement, NotistackVariantsProps>(
  (props, ref) => {
    const { id, message, description, variant, ...other } = props;

    return (
      <SnackbarContent ref={ref} role='alert' {...other}>
        <Alert
          id={`${id}`}
          severity={variant as AlertColor}
          variant='filled'
          description={description}
          title={message as string}
        />
      </SnackbarContent>
    );
  },
);

3. 验证调用代码

现在调用enqueueSnackbar时传入description参数不会再触发TypeScript错误:

import { enqueueSnackbar } from 'notistack';

enqueueSnackbar(title, {
  variant: 'error',
  description: detail,
  autoHideDuration: OTHER_SEVERITY_TIMEOUT,
});

额外注意事项

  • 确保tsconfig.json的include数组包含了自定义的.d.ts类型声明文件,让TypeScript能正确识别扩展类型。
  • 如果在组件文件内直接添加类型扩展,需确保declare module代码处于全局作用域中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 13:22:10