【问题标题】:Typescript function parameter has two types, and the property of one type can't be accessed because it is not a property of the other typeTypescript函数参数有两种类型,一种类型的属性不能访问,因为它不是另一种类型的属性
【发布时间】:2021-04-06 09:39:26
【问题描述】:

我有这个组件:

<GoogleLogin
  clientId={googleAppId}
  onSuccess={responseGoogle}
  onFailure={responseGoogle}
  isSignedIn={true}
  cookiePolicy={"single_host_origin"}
  autoLoad={false}
  icon={true}
/>

onSuccessonFailure 道具的以下功能:

const responseGoogle = (
  response: GoogleLoginResponse | GoogleLoginResponseOffline
) => {
  console.log(response.accessToken);
};

我只想使用response: GoogleLoginResponse 类型,但如果这样做,我会从库中收到以下错误:

Type '(response: GoogleLoginResponse) => void' is not assignable to type '(response: GoogleLoginResponse | GoogleLoginResponseOffline) => void'

所以我使用response: GoogleLoginResponse | GoogleLoginResponseOffline作为参数。

问题是当我尝试访问GoogleLoginResponse 类型的属性accessToken 时,出现以下错误,因为accessToken 不是GoogleLoginResponseOffline 的属性:

Property 'accessToken' does not exist on type 'GoogleLoginResponse | GoogleLoginResponseOffline'.
  Property 'accessToken' does not exist on type 'GoogleLoginResponseOffline'.

如何访问accessTokenresponse 属性?

注意事项:

【问题讨论】:

  • “我只想使用类型...”——为什么?如果不是那个怎么办?您是否以某种方式知道这不可能发生?
  • 文档表明您可以为 GoogleLogin 组件使用 accessType="online"accessType="offline" 属性(默认为“在线”)。由于我使用的是accessType="online",因此响应将是GoogleLoginResponse 类型。更多详情:github.com/anthonyjgrove/….

标签: reactjs typescript


【解决方案1】:

在您的函数中,您可以使用 type guards 通过使用类型保护来缩小类型范围。

const responseGoogle = (
  response: GoogleLoginResponse | GoogleLoginResponseOffline ): void => {
    if ('accessToken' in response ){ 
        console.log(response.accessToken);
    }else {
        console.log('offline'); 
    }
}

responseGoogle({accessToken:'abc', name: 'Jim'})
responseGoogle({name: 'Joan'})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-19
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 2015-10-28
    • 2022-01-10
    • 2021-06-13
    相关资源
    最近更新 更多