We have a React Native app that uses Redux and we've just converted most of it from Javascript to Typescript. I'm new new to Typescript so bear with me here.
As simply as i can, here's an explanation of the problem. There are two screens: SignIn
and Settings
(not our real screens but it gets the point across).
In the Redux state, there's an object:
user: { // Whatever user properties we store, id etc}
When a user signs in, user
is set. Until then, it's null
, so user: User | null
.
We use createSelector
from reselect
to fetch the user.The user is fetched on the Settings page and it can technically be null
if the user has managed to navigate there without signing in, though this isn't a real use case. To reach the Settings
page, you have to sign in. And when you sign in, the user
can no longer be null
.
In the Settings
page, when accessing e.g. user.id
, tsc
says:
error TS2531: Object is possibly 'null'
How should this be handled? Is there a way to tell Typescript (or tsc
, really) that there's no way user
can be null
on this particular screen? Or should we add a check in each screen making sure user
isn't null (even though it shouldn't be possible®)?
I prefer not to suppress the typescript error, if at all possible.
Thank you.