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

MUI Button组件Props类型异常:为何Props被推断为never?

MUI styled 中Button组件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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:12:37