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?