MUI Button组件Props类型异常:为何Props被推断为never?
问题代码
import * as React from "react"; import { styled } from "@mui/material/styles"; import MuiButton from "@mui/material/Button"; import Slider from "@mui/material/Slider"; interface Props { type: "primary" | "secondary"; } export const MySlider = styled(Slider)<Props>( (props) => ` color: ${props.type === "primary" ? "red" : "blue"}; ` ); export const MyButton = styled(MuiButton)<Props>( (props) => ` color: ${props.type === "primary" ? "green" : "gold"}; ` ); export default function App() { return <MyButton type="primary">hello</MyButton>; }
问题描述
props在Slider组件中能被正确识别类型,但在Button组件中却被推断为never类型,请问原因是什么?
原因分析
核心问题是类型冲突:
- MUI的
Button组件(即MuiButton)原生ButtonProps类型中,已包含一个type属性,类型为"button" | "submit" | "reset"。 - 你自定义的
Props中也声明了type属性,类型为"primary" | "secondary"。
当通过styled(MuiButton)<Props>传入自定义props时,TypeScript尝试合并两个类型,但两个type属性的类型完全不兼容,无法完成合并,最终导致props被推断为never类型。
而Slider组件的原生props里没有type字段,自定义type不会和原有props冲突,类型可以正常合并,因此能正确识别。
解决办法
方案一:重命名自定义props字段(最简单)
把自定义的type改成不冲突的字段名,比如customType:
interface Props { customType: "primary" | "secondary"; } export const MyButton = styled(MuiButton)<Props>( (props) => ` color: ${props.customType === "primary" ? "green" : "gold"}; ` ); // 使用时 export default function App() { return <MyButton customType="primary">hello</MyButton>; }
方案二:合并类型时排除冲突字段
通过Omit工具类型去掉Button原有type属性,再和自定义Props合并:
import * as React from "react"; import { styled } from "@mui/material/styles"; import MuiButton, { ButtonProps } from "@mui/material/Button"; import Slider from "@mui/material/Slider"; interface CustomProps { type: "primary" | "secondary"; } // 排除Button原有type,合并自定义属性 export const MyButton = styled(MuiButton)<Omit<ButtonProps, "type"> & CustomProps>( (props) => ` color: ${props.type === "primary" ? "green" : "gold"}; ` );
内容的提问来源于stack exchange,提问作者Mister Epic
相关产品推荐
相关产品推荐

