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

React+TypeScript项目中如何正确定义组件Link路由to Prop的类型

错误原因

你代码的核心问题有两个:

  1. 类型引用错误:LocationDescriptor不属于React命名空间下的类型,是react-router-dom包内置的路由类型
  2. 组件返回值标注错误:你把函数组件的返回值标注成了ChildProps,和React组件实际返回的JSX元素类型不匹配

解决方案

适配react-router v6(当前主流版本)

直接使用react-router-dom导出的原生To类型,和Link组件的to属性类型完全匹配,不会出现类型冲突:

import { Link, To } from 'react-router-dom';

interface ChildProps {
  children: React.ReactNode
  to?: To
}

// 要么删除返回值标注让TS自动推导,要么标注为JSX.Element,不要写ChildProps
export const ChildComponent = ({children, to}: ChildProps) => {
  return (
    <>
      <Link to={to}/>
      {children}
    </>
  )
}

适配react-router v5

如果使用的是v5版本,从react-router-dom导入LocationDescriptor类型即可:

import { Link, LocationDescriptor } from 'react-router-dom';

interface ChildProps {
  children: React.ReactNode
  to?: LocationDescriptor<any> 
}

export const ChildComponent = ({children, to}: ChildProps) => {
  return (
    <>
      <Link to={to}/>
      {children}
    </>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 10:54:03