I'm working with the React Google Login library in TypeScript. It has type bindings for TypeScript, but all the examples are in JavaScript, and I am pretty new to TypeScript.
The setup code looks like this:
<GoogleLogin
clientId="client-id-value"
onSuccess={successResponseGoogle}
onFailure={failureResponseGoogle}
cookiePolicy={'single_host_origin'}
/>
In TypeScript, the signature for the onSuccess callback is:
readonly onSuccess: (response: GoogleLoginResponse | GoogleLoginResponseOffline) => void
The GoogleLoginResponseOffline
type has only one property, code
, where GoogleLoginResponse
has a range of properties to access the details of the authenticated user.
The problem that I am having is that TypeScript will not let me access any of the GoogleLoginResponse properties on the response parameter, saying, for example
"Property 'getBasicProfile' does not exist on type GoogleLoginResponseOffline'"
I have tried the following to cast or check the type of the parameter, but all give errors of one type or another. My function looks like this:
const responseGoogleSuccess = (response: GoogleLoginResponse|GoogleLoginResponseOffline) => {
// Tried to check for property to identify type
if(response.googleId){ // Property 'googleId' does not exist on type 'GoogleLoginResponseOffline'
const profile = response.getBasicProfile(); // Property 'getBasicProfile' does not exist on type 'GoogleLoginResponseOffline'
}
// Tried to cast like this
const typedResponse = <GoogleLoginResponse>response;
// Tried to check type
if(response instanceof GoogleLoginResponse){ // 'GoogleLoginResponse' only refers to a type, but is being used as a value here.
}
}
It looks from the TypeScript documentation as if the if(response instanceof GoogleLoginResponse)
is close, fails in this case because GoogleLoginResponse
is an interface and it needs to be a class.
Please tell me how this is done! I've looked at lots of StackOverflow questions with similar titles, but none cover this.