我正在使用打字稿,我的 [...next-auth].tsx 文件如下所示:
import NextAuth, { Awaitable, Session, User } from "next-auth";
// import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";
type ExtendedUserType = User & { username?: string; uid?: string };
export default NextAuth({
// Configure one or more authentication providers
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
// ...add more providers here
],
pages: {
signIn: "/auth/signin", // for custom sign in page
},
callbacks: {
async session({ session, token, user }): Awaitable<Session> {
(session.user as ExtendedUserType).username = session.user?.name
?.split(" ")
.join("")
.toLocaleLowerCase();
(session.user as ExtendedUserType).uid = token.sub;
return session;
},
},
});
当使用获取会话时useSession
钩子我没有获得新添加的键的 Typescript 自动完成功能 - 'username'、'uid'
I am also getting this typescript error for Awaitable<Session>
type
上述问题的答案已讨论here https://github.com/nextauthjs/next-auth/discussions/2979
TLDR; next-auth.js.org/getting-started/typescript#module-augmentation http://next-auth.js.org/getting-started/typescript#module-augmentation
解决方案:
添加以下内容types/**/*.ts
in tsconfig.json
:
{
.
.
.
"include": ["next-env.d.ts", "types/**/*.ts", "**/*.ts", "**/*.tsx"],
.
.
.
}
然后添加以下内容session.user
.
类型/next-auth.d.ts
import NextAuth from "next-auth"
declare module "next-auth" {
/**
* Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
*/
interface Session {
user: {
/** The user's name. */
name: string
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)