anthonyjgrove / react-google-login

A React Google Login Component
https://anthonyjgrove.github.io/react-google-login
MIT License
1.85k stars 426 forks source link

typescript compatibility in onSuccess #465

Open SinisaRunjic opened 3 years ago

SinisaRunjic commented 3 years ago
type IGoogleSucces = GoogleLoginResponse | GoogleLoginResponseOffline

 const googleSuccess = async (
    res: IGoogleSucces
  ) => {
    const result = res?.profileObj;
    const token = res?.tokenId;
    try {
      dispatch({ type: 'AUTH', data:{ result, token}})
    } catch (error) {}
  };
 <GoogleLogin
      clientId="CLIENTID"
      render={googleRender}
      onSuccess={googleSuccess}
      onFailure={googleFaliure}
      cookiePolicy="single_host_origin"
    />

There is error in res?.profileObj and res?.tokenId Property 'profileObj' does not exist on type 'IGoogleSucces'. Property 'profileObj' does not exist on type 'GoogleLoginResponseOffline'

christian-predebon commented 3 years ago

You can check for the property before going ahead

function onLoginSuccess(res: GoogleLoginResponseOffline | GoogleLoginResponse) {
  if ("profileObj" in res) {
    console.log(res.profileObj) // works fine
  }
}
abhaypatil87 commented 3 years ago

This could be because GoogleLoginResponseOffline only has code as a property but GoogleLoginResponse has profileObj and tokenId, and since the response could be either, TS is never too sure if either of these properties will be present in the response object.

Frexuz commented 2 years ago

Similar issue here. GoogleLoginResponse has .accessToken, but the type doesn't know that. All I get is .code available.

if ("profileObj" in res) { is not a very good/common pattern in TS imo.