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

