Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm fighting with property
success
which is definited in API (recaptcha).
* The structure of response from the veirfy API is
* "success": true|false,
* "challenge_ts": timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
* "hostname": string, // the hostname of the site where the reCAPTCHA was solved
* "error-codes": [...] // optional
Below I tried use optional chaining to fix that problem, but it does not work. I have tried use interface on different sides, but I can't fix that again with it.
Below code:
import fetch from "node-fetch"
//...
try {
const response = await fetch(
`https://www.google.com/recaptcha/api/siteverify?secret=${process.env.GOOGLE_RECAPTCHA_SECRETKEY}&response=${captcha}`,
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
method: "POST",
const captchaValidation = await response.json();
if(captchaValidation?.success) // error: Property 'success' does not exist on type '{}'
} catch (error) {}
How can I get access to that property?
–
–
It seem shat .json is not type aware and it returns Promis<never< - .json method
I can propose a solution you need to delcare the Captcha types and tell typescript believe me it is this type
export interface CaptchaResponse {
success: boolean;
challenge_ts: string;
hostname: string;
error-codes?: any[];
const rawResponse = await response.json();
// next line is nothing more just saying - believe me it is this type. It will not do type checking
const typedRespone = rawResponse as CaptchaResponse;
if(typedRespone.success)
You can create an interface and declare that the response is that interface. Then TypeScript is told that a success property should exist.
export interface ApiResponse {
success: boolean;
challenge_ts: string;
hostname: string;
error-codes?: any[];
Then declare it as that type:
const captchaValidation: ApiResponse = await response.json();
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.