A type-safe route helper
npm install @biggerpixel/ts-route-kit
import { createRoute } from '@biggerpixel/ts-route-kit';
export const RouteKit = {
Home: createRoute('/'),
ArticleList: createRoute('/articles'),
ArticleDetail: createRoute('/articles/<int:id>'),
};
import { createRoute, RouteLinkerParams } from '@biggerpixel/ts-route-kit';
import Link from 'next/link';
import { ComponentProps } from 'react';
/**
* Create a RouteLink component that can be used to create links to routes in a type safe way
* @param routeKit - The route kit to use
* @returns A RouteLink component
* @example
* const { RouteLink } = createRouteLink(RouteKit);
*
* <RouteLink to="articleList" />;
* <RouteLink to="articleDetail" params={{ id: 2 }} />;
*/
export const RouteLink = <K extends keyof typeof RouteKit>({
to,
...props
}: {
to: K;
} & RouteLinkerParams<Parameters<(typeof RouteKit)[K]>[0]> &
Omit<ComponentProps<typeof Link>, 'href'>) => {
const routeParams = ('params' in props ? props.params : {}) as any;
return <Link href={RouteKit[to](routeParams)} {...props} />;
};
// Use in your components like:
<RouteLink to="ArticleDetail" params={{ id: 123 }}>
Your Link
</RouteLink>