简体   繁体   English

如何解决类型“从不”中不存在的属性

[英]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:我正在使用库 react-google-recaptcha 生成不可见的 ReCaptcha,我收到以下 typescript 错误:

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?我怎样才能键入 the.execute() 以便不再发生此错误? 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 ).您需要通过向 useRef 提供类型参数来告诉useRef ref 将引用的类型(因为 TypeScript 无法从初始值null推断它)。 Assuming you're using this npm package , it appears you use the type of the component:假设您正在使用npm package ,您似乎使用了组件的类型:

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

More onto this;更多关于这个; along with useRef(null) recaptcha const连同 useRef(null) recaptcha const

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

in the recaptcha component, add an onChange event as in the below snippet.在 recaptcha 组件中,添加一个 onChange 事件,如下面的代码片段所示。

  <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))请注意上面检查 recaptcha.current (if (recaptchaRef.current)) 并检查 null token (if (token)) 的行

the above will assert the possible null errors以上将断言可能的 null 错误

可能的空错误

断言后清理代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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