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

Next.js集成Firebase手机号认证时遇TypeScript类型错误

Next.js Firebase手机号认证TypeScript错误修复

问题场景

在Next.js中实现Firebase手机号认证时,触发TypeScript类型错误:Argument of type 'string' is not assignable to parameter of type 'Auth',错误出现在RecaptchaVerifier实例化的第一行代码。

相关代码

firebaseConfig.ts

// firebaseConfig.ts
import { initializeApp, FirebaseApp } from "firebase/app";
import { getAuth, Auth } from "firebase/auth";
import { getAnalytics, Analytics } from "firebase/analytics";
import { getFirestore, Firestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
  measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};

// Initialize Firebase
const app: FirebaseApp = initializeApp(firebaseConfig);
const analytics: Analytics = getAnalytics(app);
const auth: Auth = getAuth(app);
const db: Firestore = getFirestore(app);

export { app, analytics, auth, db };

报错代码片段

const appVerifier = new RecaptchaVerifier(
  "recaptcha-container", // 此行触发类型错误
  {
    size: "invisible",
  },
  auth
);

错误原因

Firebase v9+模块化SDK中,RecaptchaVerifier的构造函数参数顺序为:
new RecaptchaVerifier(auth: Auth, container: string | HTMLElement, parameters?: RecaptchaParameters)

当前参数顺序错误,将容器ID字符串放在了第一个位置(本该传入Auth实例的位置),导致TypeScript检测到类型不匹配。

解决方案

调整RecaptchaVerifier的实例化参数顺序,将Auth实例作为第一个参数传入:

修改后的代码片段

const appVerifier = new RecaptchaVerifier(
  auth, // 第一个参数传入Auth实例
  "recaptcha-container", // 第二个参数传入容器ID
  {
    size: "invisible",
  }
);

完整组件关键修改部分

const handleForwardButtonClick = () => {
  if (!error && selectedCountry && validatePhoneNumber(selectedCountry, phone)) {
    // 修正参数顺序
    const appVerifier = new RecaptchaVerifier(
      auth,
      "recaptcha-container",
      { size: "invisible" }
    );
    const phoneNumber = `+${selectedCountry.phone}${phone}`;
    signInWithPhoneNumber(auth, phoneNumber, appVerifier)
      .then((confirmationResult) => {
        setSavedPhone(phone);
        setOtpState(true);
        window.confirmationResult = confirmationResult;
      })
      .catch((error) => {
        setError("发送OTP失败,请重试。");
        console.error("signInWithPhoneNumber错误:", error);
      });
  }
};

验证要点

  1. 确保组件渲染时页面中存在ID为recaptcha-container的DOM元素
  2. 确认Firebase Auth实例已正确初始化并导入
  3. 重新编译项目,检查TypeScript错误是否消失

内容的提问来源于stack exchange,提问作者hari babu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:00:17