Skip to content

fix(react-router): fix custom link type ref inference #4121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/react-router/src/link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -364,8 +364,8 @@ type UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements
> &
React.RefAttributes<
TComp extends
| React.FC<{ ref: infer TRef }>
| React.Component<{ ref: infer TRef }>
| React.FC<{ ref: React.Ref<infer TRef> }>
| React.Component<{ ref: React.Ref<infer TRef> }>
? TRef
: never
>
Expand Down
35 changes: 35 additions & 0 deletions packages/react-router/tests/link.test-d.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expectTypeOf, test } from 'vitest'
import React from 'react'
import {
Link,
createLink,
Expand All @@ -9,6 +10,7 @@ import {
} from '../src'
import type {
CreateLinkProps,
LinkComponent,
ResolveRelativePath,
SearchSchemaInput,
} from '../src'
Expand Down Expand Up @@ -4005,6 +4007,39 @@ test('when passing a component with props to createLink and navigating to the ro
createLink((props) => expectTypeOf(props).toEqualTypeOf<CreateLinkProps>())
})

test('that createLink refs forward correctly', () => {
// copied from: https://tanstack.com/router/latest/docs/framework/react/guide/custom-link#basic-example
interface BasicLinkProps
extends React.AnchorHTMLAttributes<HTMLAnchorElement> {}
const BasicLinkComponent = React.forwardRef<
HTMLAnchorElement,
BasicLinkProps
>((props, ref) => {
return (
<a ref={ref} {...props} className={'block px-3 py-2 text-blue-700'} />
)
})
const CreatedLinkComponent = createLink(BasicLinkComponent)
const CustomLink: LinkComponent<typeof BasicLinkComponent> = (props) => {
return <CreatedLinkComponent preload={'intent'} {...props} />
}

expectTypeOf(BasicLinkComponent)
.parameter(0)
.toHaveProperty('ref')
.toEqualTypeOf<React.Ref<HTMLAnchorElement> | undefined>()

expectTypeOf(CreatedLinkComponent)
.parameter(0)
.toHaveProperty('ref')
.toEqualTypeOf<Parameters<typeof BasicLinkComponent>[0]['ref']>()

expectTypeOf(CustomLink)
.parameter(0)
.toHaveProperty('ref')
.toEqualTypeOf<Parameters<typeof BasicLinkComponent>[0]['ref']>()
})

test('ResolveRelativePath', () => {
expectTypeOf<ResolveRelativePath<'/', '/posts'>>().toEqualTypeOf<'/posts'>()

Expand Down
Loading