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

NextJS+MongoDB中better-auth扩展用户Schema遇TypeScript类型错误

解决Better-Auth扩展用户Schema后TypeScript类型不匹配问题

可能的原因及对应解决步骤

1. 确保客户端使用服务端生成的正确类型

服务端的Auth配置会自动生成匹配的客户端类型,你需要从服务端的Auth文件导出并使用,而非直接用better-auth的默认类型:

// 服务端 auth.ts
import { initAuth } from "@better-auth/react";

export const { auth, signUp, client } = initAuth({
  user: {
    additionalFields: {
      full_name: {
        type: "string",
        required: true,
      },
    },
  },
  // 其他配置项...
});

// 导出自动生成的类型
export type AuthClient = typeof client;

在客户端组件中导入并使用:

// 客户端组件文件
import { signUp } from "@/auth";

const handleRegister = async () => {
  await signUp({
    email: "test@example.com",
    password: "123456",
    full_name: "John Doe" // 此时类型应该匹配
  });
};

2. 重启TypeScript服务器与开发环境

TypeScript常存在类型缓存问题,即使配置更新也不会立刻生效:

  • 在VS Code中打开命令面板(Ctrl+Shift+P),执行「TypeScript: Restart TS Server」
  • 重启Next.js开发服务(终止进程后重新运行npm run dev)

3. 检查inferAdditionalFields插件配置

如果客户端单独初始化了better-auth实例,确保插件配置与服务端additionalFields完全一致:

// 客户端 auth_client.ts
import { createClient } from "@better-auth/react";
import { inferAdditionalFields } from "@better-auth/react/plugins";

const client = createClient({
  plugins: [
    inferAdditionalFields({
      full_name: "string" // 字段名、类型必须和服务端完全匹配
    }),
  ],
  // 其他配置项...
});

4. 清除缓存文件

若以上方法无效,手动清除缓存强制更新类型:

  • 删除项目根目录的.next文件夹
  • 删除node_modules/.cache文件夹
  • 重新执行npm install(可选)

5. 核对字段名拼写与大小写

TypeScript对大小写敏感,确保注册时传入的full_name和服务端配置的字段名完全一致,没有拼写错误。

内容的提问来源于stack exchange,提问作者David Kanevskyy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 06:53:11