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

Next.js Link组件TypeScript类型不兼容错误求助

解决方案:Next.js CommonButton组件TypeScript类型错误修复

问题根源

你的buttonGo是可选属性,类型为string | UrlObject | undefined,但Next.js Link组件的href属性不接受undefined值。当你判断buttonType === 'Link'时,TypeScript无法确保buttonGo一定存在,因此抛出类型不兼容错误。

具体修复方案

方案1:强制关联属性(推荐)

修改Props类型,确保当buttonType为'Link'时,buttonGo必须传入,从根源避免undefined:

import { useRouter } from 'next/router';
import { FC } from 'react';
import { UrlObject } from 'url';
import Link from 'next/link';

// 用联合类型拆分两种场景
type CommonButtonProps = 
  | { buttonText: string; buttonType?: Exclude<string, 'Link'>; buttonGo?: never }
  | { buttonText: string; buttonType: 'Link'; buttonGo: string | UrlObject };

const CommonButton: FC<CommonButtonProps> = ({ buttonText, buttonType, buttonGo }) => {
    const router = useRouter();

    const handleClick = () => {
        if (buttonType === 'Link' && typeof buttonGo === 'string') {
            router.push(buttonGo);
        }
    };

     return (
        <div className="mt-8 text-center">
            {buttonType === 'Link' ? (
                <Link href={buttonGo} className="bg-green-600 hover:bg-green-500 text-white py-4 px-6 rounded-lg uppercase">
                    {buttonText}
                </Link>
            ) : (
                <button className="bg-green-600 hover:bg-green-500 text-white py-4 px-6 rounded-lg uppercase">
                    {buttonText}
                </button>
            )}
        </div>
    );
};

export default CommonButton;

方案2:渲染时确保值存在

如果不想修改Props类型,可在渲染Link前添加类型守卫,确保buttonGo不为undefined:

return (
    <div className="mt-8 text-center">
        {buttonType === 'Link' && buttonGo ? (
            <Link href={buttonGo} className="bg-green-600 hover:bg-green-500 text-white py-4 px-6 rounded-lg uppercase">
                {buttonText}
            </Link>
        ) : (
            <button className="bg-green-600 hover:bg-green-500 text-white py-4 px-6 rounded-lg uppercase">
                {buttonText}
            </button>
        )}
    </div>
);

方案3:设置默认值

如果业务允许给buttonGo设置默认跳转路径,可直接给参数加默认值,消除undefined:

const CommonButton: FC<CommonButtonProps> = ({ buttonText, buttonType, buttonGo = '/' }) => {
    // ... 其余代码不变
};

为什么之前的尝试无效

你用href={{ pathname: buttonGo }}时,若buttonGo为undefined,pathname也会是undefined,仍然不符合Link组件href的类型要求,因此错误依旧。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:17:31