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

如何为Next.js组件的href属性定义正确的TypeScript类型?

解决Next.js Link组件Props中href的类型定义问题

你的问题出在Pick<LinkProps, "href">的使用上——这个方法会生成一个包含href属性的对象类型(即{ href: Url }),但Next.js的Link组件接收的href prop需要的是Url类型本身(可以是字符串或UrlObject),不是包裹它的对象,所以类型不匹配导致报错。

正确的做法是直接提取LinkProps中href属性的类型,而不是用Pick:

import React from "react";
import Link, { LinkProps } from "next/link";

// 直接获取LinkProps里href的类型
type MyComponentProps = {
  href: LinkProps['href']
}

export const MyComponent: React.FC<MyComponentProps> = ({ href }) => (
  <Link href={href}>
    <a>Some Link Text</a>
  </Link>
);

这样定义后,MyComponent的href prop就和Next.js原生Link的href类型完全一致,既支持字符串路径,也支持UrlObject(比如{ pathname: '/about', query: { id: 1 } }),类型检查就能正常通过。

如果需要同时继承Link的其他props(比如passHref、prefetch等),也可以直接扩展LinkProps并按需覆盖:

type MyComponentProps = LinkProps & {
  // 自定义额外props
  customProp?: string
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:35:33