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

TypeScript调用reCAPTCHA API时,获取success属性触发TS2339错误

解决TypeScript调用reCAPTCHA验证API时无法访问success属性的问题

问题根源

node-fetch的res.json()方法默认返回Promise<unknown>(旧版本返回Promise<{}>),TypeScript无法自动推断返回对象的具体结构,直接访问success属性就会触发TS2339错误。

正确解决步骤

1. 定义匹配API返回结构的TypeScript接口

严格按照reCAPTCHA验证API的返回格式定义接口:

interface RecaptchaValidationResponse {
  success: boolean;
  challenge_ts: string; // API返回的时间戳为字符串格式,如"2024-05-20T12:34:56Z"
  hostname: string;
  "error-codes"?: string[]; // 可选属性,带连字符的属性名需用引号包裹
}

2. 在解析JSON时指定类型

通过类型断言或泛型方法,将解析后的结果绑定到定义好的接口类型:

方法一:使用类型断言

import fetch from 'node-fetch';

async function validateRecaptcha(token: string) {
  const response = await fetch('https://www.google.com/recaptcha/api/siteverify', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: `secret=你的密钥&response=${token}`
  });

  // 紧跟json()调用做类型断言
  const captchaValidation = await response.json() as RecaptchaValidationResponse;

  // 现在可正常访问success属性
  if (captchaValidation.success) {
    // 验证通过逻辑
  } else {
    // 验证失败时可查看错误码
    console.error('验证失败:', captchaValidation["error-codes"]);
  }
}

方法二:使用泛型json方法(node-fetch v3+支持)

若使用node-fetch v3及以上版本,json()方法支持直接传入泛型参数:

const captchaValidation = await response.json<RecaptchaValidationResponse>();

3. 排查之前尝试无效的可能原因

  • 接口定义错误:比如误将success设为可选属性,或属性名拼写/格式不符(如把challenge_ts写成驼峰但未做字段转换)
  • 类型断言位置错误:若断言未紧跟json()调用,中间变量已被推断为{}类型,断言失效
  • 未校验请求状态:需先判断response.ok,避免解析错误响应导致类型不匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:55:23