I have a typeguard that check is authResponse exists. It works well, but inside await new Promise i have a compiler error, that object is possible null. I check type into deeplink condition and there is AuthResponse, but inside new Promise type is AuthResponse | null. Could you tell me, please, is it possible to make this type work correctly inside new Promise without optional chaining?
const hasAuthResponse = (
response: AuthResponse | null,
): response is AuthResponse => !!response;
if (hasAuthResponse(authResponse)) {
const deepLink = getRedirectDeepLink(
redirect_to_scheme,
"",
allowedSchemas ?? undefined,
);
if (deepLink) {
router.push({
pathname: deepLink,
query: {
rsid: authResponse.rsid,
},
});
return;
}
await new Promise<void>((resolve) => {
helper
? helper.propagateSession(
authResponse.rsid,
{
back: back ?? Urls.PROFILE,
},
resolve,
)
: resolve();
});
}
CodePudding user response:
Your example isn't quite complete, but I'd wager authResponse
is probably not const
.
Since the promise call is asynchronous, TypeScript infers that the value of authResponse
could have become null
by the time propagateSession
gets called.
The easy fix is to rebind authResponse
into a local name and use that (since it's guaranteed that its type will remain AuthResponse
):
if (hasAuthResponse(authResponse)) {
const authResponse2 = authResponse; // inferred type: AuthResponse
but since you only really use the rsid
field from the AuthResponse, you can just destructure it out of the authResponse
and use it in the subsequent calls:
if (hasAuthResponse(authResponse)) {
const {rsid} = authResponse;