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

styled创建的MUI ListItemButton指定component为Link时TS校验失败如何解决?

问题解决方法

原因

你在使用MUI styled 包装ListItemButton时,没有显式保留组件的完整props类型定义,导致TypeScript丢失了对component这类多态属性的识别,也无法识别传入Link后对应的to等专属属性。

解决方案

修改NavigationListItemButton的定义,给styled方法显式传入ListItemButtonProps泛型参数,完整保留原组件的类型定义:

import { Theme, styled, alpha, ListItemButtonProps } from '@mui/material';
import ListItemButton from '@mui/material/ListItemButton';

const NavigationListItemButton = styled(ListItemButton)<ListItemButtonProps>(
  ({ theme }) => ({
    '&:hover': {
      backgroundColor: alpha(theme.palette.secondary.main, 0.5),
    },
  }),
);

export default NavigationListItemButton;

补充说明

修改后你原有调用代码无需任何改动,TypeScript会自动校验你传入component属性的组件对应的所有props,除了Link的to属性外,其他自定义组件的props也会获得正确的类型提示和校验。
不推荐使用any类型断言的临时修复方案,会丢失TypeScript的类型保护能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:06:01