In my React application I'm using the non-null assertion (!) to tell TS that the value coming from useContext hook is not null. It works well and seems to be the textbook use-case for non-null assertion, but with the recommended eslint rules non-null assertion is a warning.
Being new to TypeScript I want to make sure that I'm not missing a common pattern or best practice approach when dealing with these situations. Or maybe there is a different way to type the user object in the example below.
- State is defined in a standalone file.
// context.ts
interface State {
user: User | null; // User type is defined elsewhere, has 'id' and 'email'
}
const state: State = {
user: null,
};
- If user is logged in
state.userin defined.
// App.tsx
return state.user ? <Dashboard /> : <Login />;
- User can only see the Dashboard if
state.useris not null, but I still see the following errors.
// Dashboard.tsx
const { state } = React.useContext(context);
const name = state.user.firstName; // Object is possibly 'null'.
const { id, email } = state.user; // Property 'id/email' does not exist on type 'User | null'.
- Logout method sets
state = { user: null }so null has to be assignable to theUsertype.
Anticipating potential answers that don't address my question about best practice/patterns:
I know how to disable
@typescript-eslint/no-non-null-assertionrule, this isn't the solution I'm looking for.I am aware that I can avoid both the errors and the non-null assertion warning if I use optional chaining in the first example like so:
const name = state.user?.firstName;, but this doesn't answer my question. I'd actually prefer non-null assertion in this case, because would be more explicit.
Thanks!