typescript - 类型 "AppRouterInstance" 不能分配给类型 "nextRouter"
在我的 Next.js 项目中,我有一个如下所示的注册表单:
"use client";
import * as React from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { cn } from "@/lib/util";
import { userAuthSchema } from "@/lib/validations/auth";
import { buttonVariants } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Icons } from "@/components/icons";
import { useRouter } from "next/navigation";
import { registerUser } from "@/lib/register-user";
export type FormData = z.infer<typeof userAuthSchema>;
export function RegisterForm() {
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm<FormData>({ resolver: zodResolver(userAuthSchema) });
const [isLoading, setIsLoading] = React.useState<boolean>(false);
const [error, setError] = React.useState<string | null>(null);
const router = useRouter();
async function onSubmit(submittedData: FormData) {
await registerUser({submittedData, setError, setIsLoading, reset, router})
}
return (
<div>
{error && <p className="mb-5 text-sm text-red-500 animate-in fade-in-0 slide-in-from-left-1">{error}</p>}
<form onSubmit={handleSubmit(onSubmit)}>
<div className="grid gap-6">
<div className="grid gap-1">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="[email "
autoCapitalize="none"
autoComplete="email"
autoCorrect="off"
disabled={isLoading}
{...register("email")}
/>
{errors.email && (
<p className="px-1 text-xs text-red-600 animate-in fade-in-0 slide-in-from-left-1">
{errors.email.message}
</p>
)}
</div>
<div className="grid gap-1">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
autoCapitalize="none"
autoComplete="off"
autoCorrect="off"
disabled={isLoading}
{...register("password")}
/>
{errors.password && (
<p className="px-1 text-xs text-red-600 animate-in fade-in-0 slide-in-from-left-1">
{errors.password.message}
</p>
)}
</div>
<button className={cn(buttonVariants())} disabled={isLoading}>
{isLoading && (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
)}
Register
</button>
</div>
</form>
</div>
);
}
注意我正在将一个 router 参数传递给 registerUser() 函数:
async function onSubmit(submittedData: FormData) {
await registerUser({submittedData, setError, setIsLoading, reset, router})
}
这里是 registerUser 函数:
import "client-only";
import type { FormData } from "@/components/auth/register-form";
import { NextRouter } from "next/router";
const RESPONSE_MESSAGES = {
USER_DOCUMENT_CREATED: "New user document created",
USER_DOCUMENT_UPDATED: "Existing user document updated",
USER_ALREADY_REGISTERED: "User already registered",
EMAIL_VERIFICATION_LINK_SENT: "Email verification link sent",
EMAIL_VERIFICATION_LINK_ALREADY_SENT:
"Email verification link already sent. Please check your inbox and verify your email.",
REGISTRATION_FAILED: "Registration failed. Please try again.",
};
interface RegisterUserProps {
submittedData: FormData;
setError: React.Dispatch<React.SetStateAction<string | null>>;
reset: () => void;
setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;
router: NextRouter;
}
export async function registerUser({
submittedData,
setError,
reset,
setIsLoading,
router,
}: RegisterUserProps) {
setIsLoading(true);
setError(null);
try {
// Attempt to register the user
const registerResponse = await fetch("/api/register", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(submittedData),
});
// Registration failed
if (!registerResponse.ok) {
throw new Error(RESPONSE_MESSAGES.REGISTRATION_FAILED);
}
const registerResponseData = await registerResponse.json();
// User already registered
if (
registerResponseData.message === RESPONSE_MESSAGES.USER_ALREADY_REGISTERED
) {
setError(RESPONSE_MESSAGES.USER_ALREADY_REGISTERED);
reset();
return;
}
// Email verification link was already sent
if (
registerResponseData.message ===
RESPONSE_MESSAGES.EMAIL_VERIFICATION_LINK_ALREADY_SENT
) {
setError(RESPONSE_MESSAGES.EMAIL_VERIFICATION_LINK_ALREADY_SENT);
reset();
return;
}
// New user. Send email verification link
if (
registerResponseData.message ===
RESPONSE_MESSAGES.USER_DOCUMENT_CREATED ||
registerResponseData.message === RESPONSE_MESSAGES.USER_DOCUMENT_UPDATED
) {
const { email, emailVerificationToken } = registerResponseData;
const emailResponse = await fetch(
"/api/send-registration-email-verification-link",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, emailVerificationToken }),
},
);
// Check if email was successfully sent
if (!emailResponse.ok) {
throw new Error(RESPONSE_MESSAGES.REGISTRATION_FAILED);
}
const emailResponseData = await emailResponse.json();
if (
emailResponseData.message ===
RESPONSE_MESSAGES.EMAIL_VERIFICATION_LINK_SENT
) {
reset();
router.replace("/register/verify-email");
}
}
} catch (error) {
setError((error as Error).message);
} finally {
setIsLoading(false);
}
}
如你所见,我已经用 NextRouter 对 router 进行了类型注解:
interface RegisterUserProps {
submittedData: FormData;
setError: React.Dispatch<React.SetStateAction<string | null>>;
reset: () => void;
setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;
router: NextRouter;
}
然而,当我这样做时,我在 RegisterForm 组件中的 router 下方看到一条红色波浪线。
错误显示如下:
Type 'AppRouterInstance' is not assignable to type 'NextRouter'.
Type 'AppRouterInstance' is missing the following properties from type 'BaseRouter': route, pathname, query, asPath, and 2 more.ts(2322)
register-user.ts(20, 3): The expected type comes from property 'router' which is declared here on type 'RegisterUserProps'
(property) RegisterUserProps.router: NextRouter
有人能向我解释这里发生了什么吗?我该如何修复这个 TypeScript 错误?
答案#1
Next.js 有两个 useRouter。旧的可以从 'next/router' 导入,v13+ 的新的可以从 'next/navigation' 导入
旧的 useRouter 类型是 NextRouter,新的类型是 AppRouterInstance
你在组件中使用了 new,但在函数中输入了 old。
我在类似情况下使用的一个技巧是不导入类型,而是让 Typescript 通过 UseRouter: typeof useRouter 推断函数的类型,并使用 ReturnType 辅助工具获取返回类型 type router=ReturnType<typeof useRouter>
更新
因为实际上并不需要这种类型,Next.js 团队并没有直接导出它。但你仍然可以导入内部类型 import { AppRouterInstance } from "next/dist/shared/lib/app-router-context"
答案#2
在 Next.js 15.1.3 中,你可以像这样导入 AppRouterInstance 类型:
import { AppRouterInstance } from 'next/dist/shared/lib/app-router-context.shared-runtime'
