Next.js/TypeScript中“No overload matches this call”类型错误求助
问题原因
你遇到的"No overload matches this call"错误,本质是自定义的ButtonProps类型和内部使用的SignInBtn组件的多态props不兼容:
- 当传递
href时,SignInBtn会切换为锚点(<a>)元素的props规范,但你的ButtonProps里的onClick事件类型是针对<button>元素的,两者类型冲突; - 多态组件会根据是否存在
href来区分接收的props类型,你的混合式props定义打破了这种类型约束。
修复方案
1. 拆分props类型,区分按钮与锚点场景
先定义基础公共props,再分别定义按钮和锚点专属的props,最后合并为联合类型:
import React from 'react'; // 公共属性 type BaseButtonProps = { children?: React.ReactNode; color?: 'primary' | 'secondary'; disabled?: boolean; }; // 纯按钮的props(无href) type ButtonOnlyProps = BaseButtonProps & { href?: never; onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void; }; // 锚点按钮的props(必须有href) type AnchorButtonProps = BaseButtonProps & { href: string; onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void; }; // 最终的ButtonProps类型 type ButtonProps = ButtonOnlyProps | AnchorButtonProps;
2. 适配组件渲染逻辑
根据href是否存在,给SignInBtn传递对应类型的props:
const Button = (props: ButtonProps) => { const { href, children, ...rest } = props; return ( <BtnSection> {href ? ( <SignInBtn href={href} {...rest as AnchorButtonProps}> {children} </SignInBtn> ) : ( <SignInBtn {...rest as ButtonOnlyProps}> {children} </SignInBtn> )} <Icon src={icon} width="24" height="24"/> </BtnSection> ); };
备选方案:利用多态组件的as属性(如果SignInBtn支持)
如果你的SignInBtn是支持as属性的多态组件(比如MUI Button、Next.js Link等),可以更简洁地处理:
const Button = (props: ButtonProps) => { const { href, children, ...rest } = props; return ( <BtnSection> <SignInBtn as={href ? 'a' : 'button'} href={href} {...rest} > {children} </SignInBtn> <Icon src={icon} width="24" height="24"/> </BtnSection> ); };
内容的提问来源于stack exchange,提问作者Ihesinulo Israel
相关产品推荐
相关产品推荐

