T
TanStack9mo ago
adverse-sapphire

Loosing type safety when wrapping <Link>

Anyone have an idea on how to keep type safety while wrapping <Link> in a generic component like so? Right now typescript allows me to provide invalid routes like so <Link to="/invalid"> and I don't like that I loose the type safety.
import { Link } from "@tanstack/react-router";
import clsx from "clsx";
import type { ComponentProps, ReactNode } from "react";

export const Anchor = ({
className,
children,
...props
}: ComponentProps<typeof Link> & {
children: ReactNode;
className?: string;
}) => {
return (
<Link
className={clsx("hover:underline text-amber-700 font-medium", className)}
{...props}
>
{children}
</Link>
);
};
import { Link } from "@tanstack/react-router";
import clsx from "clsx";
import type { ComponentProps, ReactNode } from "react";

export const Anchor = ({
className,
children,
...props
}: ComponentProps<typeof Link> & {
children: ReactNode;
className?: string;
}) => {
return (
<Link
className={clsx("hover:underline text-amber-700 font-medium", className)}
{...props}
>
{children}
</Link>
);
};
4 Replies
xenial-black
xenial-black9mo ago
Custom Link | TanStack Router React Docs
While repeating yourself can be acceptable in many situations, you might find that you do it too often. At times, you may want to create cross-cutting components with additional behavior or styles. Yo...
magic-amber
magic-amber2mo ago
@thehornta what did the end result look like, the linked docs only talk about custom link components, not having type safe props for the official <Link/> component.
adverse-sapphire
adverse-sapphire2mo ago
Type Utilities | TanStack Router React Docs
Most types exposed by TanStack Router are internal, subject to breaking changes and not always easy to use. That is why TanStack Router has a subset of exposed types focused on ease of use with the in...
magic-amber
magic-amber2mo ago
Perfect, thank you

Did you find this page helpful?