I'm trying to implement an auth function for user roles using typescript and firebase/store and have noticed something strange when type guards are used in async functions. Specifically with .then()
.
The following is a snippet of the code with the issue (out of context for brevity):
authUser: firebase.User | null;
...
if (authUser) {
this.user(authUser.uid)
.get()
.then(snapshot => {
const dbUser = snapshot.data();
if (dbUser && !dbUser.roles) dbUser.roles = {};
authUser = {
uid: authUser.uid,
email: authUser.email,
emailVerified: authUser.emailVerified,
providerData: authUser.providerData,
...dbUser,
};
next(authUser);
});
} else {
...
}
The typescript compiler is complaining that in the authUser = { uid: authuser.uid ... }
block, authUser
is possibly null
. How is this possible when it's within the if
statement? Does this have something to do with the fact that the function is async?
While authUser was not null when you fired the promise, it MAY BE null when the promise is fulfilled depending on timing. Thus the compiler is rightly complaining that it may be null. Remember that happens later, at an undetermined time, and other code may have changed it by then.
You will need to check and handle the case in the then to handle any timing scenarios that may crop up.