TanStackT
TanStack3mo ago
11 replies
sad-indigo

Type inference gap between Tanstack Start and Tanstack Query

When a TanStack Start loader redirects based on query data (like redirecting if user is null), the runtime guarantees the route will never render in that state.

But TypeScript doesn’t pick that up — it still infers user as User | null in the component.

export const Route = createFileRoute('/(app)')({
  component: RouteComponent,

  async loader({ context }) {
    const { queryClient } = context

    const { user } = await queryClient.ensureQueryData(
      authUserQueryOptions(),
    )

    if (!user) {
      throw redirect({
        to: '/auth/login'
      })
    }
  },
})

function RouteComponent() {
  const {
    data: { user }, // <-- user can still be undefined
  } = useSuspenseQuery(authUserQueryOptions())

  return (
    <>
      <Header user={user} />
      <Outlet />
      <AsideNav />
    </>
  )
}


Problem

The loader guarantees that user isn’t null, but TypeScript doesn’t know that — so you have to use a null assertion or redundant check.

Question

Is there a recommended way to tell TypeScript that the redirect ensures non-null data for this route without null assertions?
Was this page helpful?