要在 TypeScript 中扩展 NextAuth 的 Session
类型,可以按照以下步骤操作:
- 创建一个
next-auth.d.ts
文件。 - 在这个文件中扩展
next-auth
模块的Session
接口。
以下是一个完整的示例:
// next-auth.d.ts import "next-auth"; // 扩展 next-auth 模块 declare module "next-auth" { // 扩展 User 接口 interface User { id: number; // 或 string,根据你的需求 // 其他自定义字段 } // 扩展 Session 接口 interface Session { user: User; } }
确保在你的 tsconfig.json
文件中包含类型声明文件的位置:
{ "compilerOptions": { "typeRoots": ["./node_modules/@types", "./path/to/your/types"] } }
在实际使用中,可以通过 useSession
或 getSession
方法获取扩展后的 Session
类型:
import { useSession } from "next-auth/react"; const Component = () => { const { data: session } = useSession(); if (session) { console.log(session.user.id); // 访问扩展后的 user.id 字段 } return <div>{session?.user?.name}</div>; };
如果在某些情况下,类型定义没有按预期工作,可以尝试将声明文件放在项目的根目录,并确保 tsconfig.json
中正确配置了类型路径。如果问题依旧存在,可以参考官方文档中的 TypeScript 指南 进行进一步调整。