NextAuth中User|AdapterUser类型不存在role属性的TypeScript错误
解决NextAuth自定义字段的TypeScript类型错误
问题根源
NextAuth的默认User、Session、JWT类型未包含你自定义的role和id字段,导致TypeScript无法识别这些属性。
解决方案
1. 扩展NextAuth类型定义
在项目根目录创建types/next-auth.d.ts文件,添加以下代码扩展默认接口:
import NextAuth from "next-auth"; declare module "next-auth" { // 扩展User类型,添加自定义字段 interface User { id: string; role: number; } // 扩展Session类型,添加自定义字段 interface Session { id: string; role: number; } } declare module "next-auth/jwt" { // 扩展JWT类型,添加自定义字段 interface JWT { id: string; role: number; } }
2. 确保TypeScript识别类型文件
修改tsconfig.json的include配置,确保包含上述类型文件:
{ "compilerOptions": { // 保留原有配置... }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "types/**/*.d.ts"] }
3. 验证回调代码
你的原回调代码逻辑无需修改,扩展类型后TypeScript会自动识别user.role、session.id等字段,类型错误将消失。
说明
通过声明模块扩展NextAuth的默认接口,TypeScript就能识别你在authorize中返回的自定义用户字段,同时解决JWT和Session回调中的类型不匹配问题。
内容的提问来源于stack exchange,提问作者Nextrati
相关产品推荐
相关产品推荐

