自定义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
相关产品推荐
相关产品推荐

