简体   繁体   中英

How to solve Property does not exist in type 'never'

I'm using the library react-google-recaptcha to generate invisible ReCaptcha and I get the follow typescript error:

Property 'execute' does not exist in type 'never'

This is the code:

  const recaptcha = useRef(null);

  useEffect(() => {
    let token;
    if (recaptchaLoaded) {
      token = recaptcha.current?.execute();
    }
  }, [recaptchaLoaded]);
  
  
   <ReCAPTCHA
      ref={recaptcha}
      sitekey={SITE_KEY}
    />

How can I type the.execute() so that this error doesn't happen anymore? Or should I do it another way?

Thanks

You need to tell TypeScript the type of what the ref will refer to by providing a type argument to useRef (since TypeScript can't infer it from the initial value null ). Assuming you're using this npm package , it appears you use the type of the component:

const recaptcha = useRef<ReCAPTCHA>(null);
//                      ^^^^^^^^^^^

More onto this; along with useRef(null) recaptcha const

const recaptcha = useRef<ReCAPTCHA>(null);
//                       ^^^^^^^^^   

in the recaptcha component, add an onChange event as in the below snippet.

  <ReCAPTCHA
    ref={recaptchaRef}
    onChange={handleCaptchaChange}
    sitekey="yourSiteKey"
  />


const handleCaptchaChange = () => {
    if (recaptchaRef.current) {
        const token = recaptchaRef.current.getValue();
        if (token)
            setSaveButtonDisabled(token.length <= 0);
    }
}

note the lines above where you are checking for recaptcha.current (if (recaptchaRef.current)) and check for null token (if (token))

the above will assert the possible null errors

可能的空错误

断言后清理代码

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM