如何为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
相关产品推荐
相关产品推荐

