You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NextAuth中正确定义signIn回调函数的参数类型?

解决NextAuth.js中TypeScript类型错误问题

你遇到的TypeScript错误是因为没有给authOptions和回调参数指定正确的类型,NextAuth.js提供了内置类型,不需要自定义接口,直接使用即可。

步骤1:导入必要的类型

从next-auth和GitHub提供者中导入对应的类型:

import NextAuth, { AuthOptions, User, Account } from "next-auth"
import GithubProvider, { GithubProfile } from "next-auth/providers/github"
import { fauna } from '../../../services/fauna'
import { query as q } from 'faunadb'

步骤2:给authOptions指定AuthOptions类型

这能让TypeScript自动推断回调函数的参数类型,同时解决悬停时的类型提示问题:

export const authOptions: AuthOptions = {
    providers: [
        GithubProvider({
            clientId: process.env.GITHUB_ID!,
            clientSecret: process.env.GITHUB_SECRET!,
            authorization: {
                params: {
                    scope: 'read:user'
                }
            }
        }),
    ],
    callbacks: {
        // 显式指定参数类型(可选,但更清晰)
        async signIn({ user, account, profile }: { user: User; account: Account; profile: GithubProfile }) {
            // 先检查email是否存在,避免可选类型错误
            if (!user.email) return false;
            
            const { email } = user

            try {
                await fauna.query(
                    q.If(
                        q.Not(
                            q.Exists(
                                q.Match(
                                    q.Index('user_by_email'),
                                    q.Casefold(user.email)
                                )
                            )
                        ),
                        q.Create(
                            q.Collection('users'),
                            { data: { email } }
                        ),
                        q.Get(
                            q.Match(
                                q.Index('user_by_email'),
                                q.Casefold(user.email)
                            )
                        )
                    )
                )
                return true

            } catch {
                console.log('no permission')
                return false
            }

        }
    }
}

export default NextAuth(authOptions)

关键说明

  1. AuthOptions类型:用于约束整个authOptions对象,TypeScript会自动校验配置项的合法性,并推断回调函数的参数类型。
  2. 回调参数类型:User、Account是NextAuth的通用类型,GithubProfile是GitHub提供者专属的profile类型,能让TypeScript识别GitHub返回的profile字段。
  3. email非空检查:User类型中的email是可选字段,添加检查可以避免类型错误,同时提升代码健壮性。

修改后,VSCode的TypeScript错误会消失,悬停authOptions时也会显示正确的类型提示。

内容的提问来源于stack exchange,提问作者Flavio Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 11:50:23