You need to enable JavaScript to run this app. 使用Web OTP API时TypeScript报CredentialType不存在code属性如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用Web OTP API时TypeScript报CredentialType不存在code属性如何解决

错误本质

这个报错是Web OTP API开发中非常常见的TypeScript类型适配问题,核心原因是TypeScript内置的通用Credential类型定义未完全覆盖Web OTP API的专属能力:
navigator.credentials.get()方法的默认返回值是通用Credential联合类型,这个类型仅定义了所有Credential子类共有的基础属性(如id、type),不会包含OTP场景下专属的code字段,因此直接访问content.code时TS会抛出属性不存在的校验错误。

解决方案

方案1:手动补全全局缺失的类型定义(长期维护推荐)

不需要引入第三方依赖,直接在项目全局类型声明文件(通常是src/types/global.d.ts)中补全Web OTP API的类型定义即可:

// 定义OTP凭证的专属类型
interface OTPCredential extends Credential {
  /** 短信中提取到的一次性验证码 */
  code: string;
}

// 扩展CredentialRequestOptions的otp配置类型
interface CredentialRequestOptions {
  otp?: {
    /** 支持的传输渠道,目前仅支持sms */
    transport: Array<'sms'>;
  };
}

// 重载credentials.get方法的返回类型,传入otp配置时正确推导返回值类型
interface CredentialsContainer {
  get(
    options: CredentialRequestOptions & { otp: { transport: Array<'sms'> } }
  ): Promise<OTPCredential>;
}

补全完成后,TS会自动对credentials.get()的返回值做类型推导,content的类型会被正确识别为OTPCredential,访问code属性就不会再触发报错。

方案2:临时类型断言(快速调试推荐)

如果不想修改全局类型配置,也可以在获取返回值时直接做类型断言,跳过TS的通用类型校验:

const content = await navigator.credentials.get(o) as OTPCredential;
// 可正常访问code属性
console.log(content.code);

注意:这种方式没有完整的类型保护,仅适合临时调试使用,长期维护的项目更推荐使用方案1补全全局类型。

原示例代码的语法问题修正

你提供的示例代码还存在两处会导致运行异常的问题,可一并修正:

  • 原代码中的catch回调没有对应的try块包裹,会触发语法错误,需要将获取凭证的异步逻辑放入try块中
  • 10秒超时的定时器没有在凭证获取成功、请求被终止的场景下清理,会造成内存泄漏

修正后的可正常运行的代码参考:

async otpRequest() {
  if (!('OTPCredential' in window)) return;

  const abortController = new AbortController();
  const timer = setTimeout(() => {
    abortController.abort();
  }, 10 * 1000);

  try {
    const requestOptions: CredentialRequestOptions = {
      otp: { transport: ['sms'] },
      signal: abortController.signal
    };

    const content = await navigator.credentials.get(requestOptions);
    // 成功获取后清理定时器
    clearTimeout(timer);
    console.log(content.code);
  } catch (err) {
    // 异常终止时清理定时器
    clearTimeout(timer);
    console.log(err);
  }
}

内容的提问来源于stack exchange,提问作者Carlos A. Rabello Portella

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 09:24:04