DX Generate Router
타입 오버라이드 사용하기
Next.js의 라우터 타입을 오버라이드하여 타입 안전성을 높이는 방법을 알아봅니다.
타입 오버라이드
generate-router는 아래의 타입 생성 파일을 추출하고 Next.js의 useRouter와 Link 컴포넌트의 타입을 오버라이드하여 타입 안전성을 제공합니다.
hljs typescripttype StaticPaths =
| '/'
| '/about';
type DynamicPaths =
| `/user/${string}`;
type RoutePath = StaticPaths | DynamicPaths | `${StaticPaths}?${string}`;
// Next.js 라우터 타입 오버라이드 (--override 옵션 사용 시)
declare module 'next/router' {
interface UrlObject {
pathname: RoutePath;
query?: { [key: string]: string | number | boolean | readonly string[] | undefined };
hash?: string;
}
interface NextRouter extends Omit<import('next/dist/shared/lib/router/router').NextRouter, 'push' | 'replace'> {
push(
url: RoutePath | UrlObject,
as?: string | UrlObject,
options?: TransitionOptions
): Promise<boolean>;
replace(
url: RoutePath | UrlObject,
as?: string | UrlObject,
options?: TransitionOptions
): Promise<boolean>;
}
export function useRouter(): NextRouter;
}
declare module 'next/navigation' {
interface NavigationUrlObject {
pathname: RoutePath;
query?: { [key: string]: string | number | boolean | readonly string[] | undefined };
hash?: string;
}
interface NavigationRouter extends Omit<import('next/dist/shared/lib/app-router-context.shared-runtime').AppRouterInstance, 'push' | 'replace'> {
push(href: RoutePath | NavigationUrlObject, options?: { scroll?: boolean }): void;
replace(href: RoutePath | NavigationUrlObject, options?: { scroll?: boolean }): void;
query: { [key: string]: string | string[] | undefined };
}
export { NavigationRouter };
export function useRouter(): NavigationRouter;
export function usePathname(): RoutePath;
export function useSearchParams(): URLSearchParams & {
get(key: string): string | null;
getAll(): { [key: string]: string | string[] };
};
}
declare module 'next/link' {
export interface LinkProps
extends Omit<import('next/dist/client/link').LinkProps, 'href'> {
href:
| RoutePath
| {
pathname: RoutePath;
query?: {
[key: string]:
| string
| number
| boolean
| readonly string[]
| undefined;
};
hash?: string;
};
}
export default function Link(props: LinkProps): JSX.Element;
}
useRouter 타입 오버라이드
hljs typescript// 올바른 사용
router.push('/about'); // 정상 작동
router.push('/user/123'); // 정상 작동
// 잘못된 사용
router.push('/invalid-path'); // 컴파일 에러
Link 컴포넌트 타입 오버라이드
hljs typescript// 올바른 사용
<Link href="/about">About</Link> // 정상 작동
<Link href="/user/123">User</Link> // 정상 작동
// 잘못된 사용
<Link href="/undefined-route">Invalid</Link> // 컴파일 에러
쿼리 파라미터 제공
hljs typescripttype RoutePath = StaticPaths | DynamicPaths | `${StaticPaths}?${string}`;
위에서 생성되는 쿼리 스트링을 통해 다양한 쿼리에 대응이 가능합니다.