【问题标题】:typescript custom component function param throwing warning打字稿自定义组件函数参数抛出警告
【发布时间】:2020-06-02 02:29:25
【问题描述】:

我有这段代码

<GoogleLogin
  onSuccess={responseGoogle => {
    const { email, name } = responseGoogle.profileObj; // error: Property 'profileObj' does not exist on type 'GoogleLoginResponse | GoogleLoginResponseOffline'.
  }}
/>

图书馆在这里https://www.npmjs.com/package/react-google-login

我该怎么办?我试过(responseGoogle:any)它不起作用。

【问题讨论】:

    标签: javascript reactjs typescript ecmascript-6


    【解决方案1】:

    您必须指定登录响应类型。它可以是GoogleLoginResponseOfflineGoogleLoginResponse。属性profileObj 仅存在于GoogleLoginResponse 中。如果您请求离线访问,则响应中将只有一个code,您应该使用GoogleLoginResponseOffline 类型。

    <GoogleLogin
            onSuccess={(responseGoogle: GoogleLoginResponse) => {
              const { email, name } = responseGoogle.profileObj; 
    
            }}
          />
    

    【讨论】:

    • 我收到了Cannot find name 'GoogleLoginResponse'的错误
    • 您需要添加import { GoogleLoginResponse } from 'react-google-login';
    【解决方案2】:

    试试这个

      <GoogleLogin
        onSuccess={(responseGoogle: GoogleLoginResponse ) => {
          const { email, name } = responseGoogle.profileObj
    
        }}
      />
    

    或者你也可以使用 as 关键字让打字稿知道它是GoogleLoginResponse 类型,而不是把它误解为GoogleLoginResponseOffline

    【讨论】:

      【解决方案3】:

      试试这个

      <GoogleLogin
        onSuccess={({ profileObj: { email, name } = {} }: any) => {
          // use email and name
        }
      />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-20
        • 2020-02-16
        • 1970-01-01
        • 1970-01-01
        • 2019-08-03
        • 2021-07-05
        • 2020-04-13
        • 2023-02-20
        相关资源
        最近更新 更多