Skip to content

help with typization in React/Redux and null handling #4776

Answered by EskiMojo14
deep-kun asked this question in Help
Discussion options

You must be logged in to vote

it's probably not the recommended approach, but I like to use an assert helper (also known as invariant) inside selectors for things that should never happen but still need to be proved to typescript. that way if the thing that should never happen happens, i get an intuitive error message rather than "tried to read property of undefined" or whatever. for example:

function assert(condition: unknown, message: string): asserts condition {
  if (!condition) throw new Error(message)
}

const selectNullableUser = (state: RootState) => state.user.user;
const selectUser = (state: RootState) => {
  const user = selectNullableUser(state);
  assert(user, "Only call selectUser if you know user is def…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@deep-kun
Comment options

Answer selected by deep-kun
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
3 participants