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

如何全局定义TypeScript类型以支持通知组件的data属性?

全局扩展notistack的SnackbarProps类型以支持data-testid

你可以通过TypeScript的模块扩展特性,在项目中全局定义一次类型,避免在每个使用文件中重复编写局部类型。具体步骤如下:

  1. 创建全局类型声明文件
    在项目的类型目录(比如src/types/)下新建notistack.d.ts文件,内容如下:
import type React from 'react';

declare module 'notistack' {
  interface SnackbarProps extends React.HTMLAttributes<HTMLDivElement> {
    'data-testid'?: string;
  }
}
  1. 确保TypeScript识别该文件
    检查项目的tsconfig.json,确保include字段包含了这个类型文件所在的路径,比如:
{
  "compilerOptions": {
    // 你的其他编译配置
  },
  "include": [
    "src/**/*",
    "src/types/**/*.d.ts"
  ]
}
  1. 直接使用无需重复定义
    完成上述配置后,所有使用notistack的文件里,都可以直接给SnackbarProps添加data-testid属性,无需局部类型或断言:
import { useSnackbar } from 'notistack';

const { enqueueSnackbar } = useSnackbar();
enqueueSnackbar('message', {
  variant: 'success',
  SnackbarProps: { 'data-testid': 'notification' }
});

这种方式利用了TypeScript对模块类型的扩展能力,直接增强了notistack库的原有类型定义,全局生效且无需重复代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:47:02