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

Next.js发布npm包时遭遇UNDEFINED_VOID_ONLY类型错误

解决方案:解决TypeScript声明构建时的UNDEFINED_VOID_ONLY类型错误

1. 显式指定组件类型,规避隐式依赖

给DrawerHeaderStyled明确标注类型,避免TypeScript自动推断出依赖@types/react/canary的实验性类型。示例代码:

import { styled } from '@mui/material/styles';
import { DrawerHeader } from '@mui/material';

// 直接将样式化组件断言为原组件类型
const DrawerHeaderStyled = styled(DrawerHeader)(({ theme }) => ({
  // 你的样式逻辑
})) as typeof DrawerHeader;

export default DrawerHeaderStyled;

或者更严谨地通过ComponentType约束:

import type { ComponentType } from 'react';
import { styled } from '@mui/material/styles';
import { DrawerHeader } from '@mui/material';

const StyledComponent = styled(DrawerHeader)(({ theme }) => ({
  // 样式定义
}));

const DrawerHeaderStyled: ComponentType<typeof DrawerHeader> = StyledComponent;

export default DrawerHeaderStyled;

2. 调整tsconfig.json排除实验性类型依赖

在tsconfig.json中明确排除@types/react/canary,并指定使用稳定版React类型:

{
  "compilerOptions": {
    // 其他原有配置
    "types": ["react", "@types/node", "@mui/material"],
    "skipLibCheck": true // 可选:跳过第三方库类型检查,避免实验性类型干扰
  },
  "exclude": ["node_modules/@types/react/canary"]
}

3. 锁定@types/react稳定版本

@types/react/canary是实验性类型包,大概率是依赖树中某个包间接引入的。在package.json中锁定稳定版@types/react:

{
  "devDependencies": {
    "@types/react": "^18.2.66",
    "@types/react-dom": "^18.2.22"
  }
}

执行npm install重新安装依赖,确保依赖树中不再包含canary版本。

4. 手动编写组件类型声明文件

如果自动生成声明仍有问题,可单独创建.d.ts文件手动声明组件类型:

// src/components/DrawerHeaderStyled.d.ts
import { DrawerHeader } from '@mui/material';

declare const DrawerHeaderStyled: typeof DrawerHeader;

export default DrawerHeaderStyled;

同时在tsconfig.json中确保该文件被包含:

{
  "include": ["src/**/*", "src/components/*.d.ts"]
}

内容的提问来源于stack exchange,提问作者Troels Skytte Kaspersen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 19:02:04