Skip to content

How to properly type guard to avoid "possibly undefined" #181

Answered by DamianOsipiuk
Vincent-HD asked this question in Q&A

You must be logged in to vote

So the typing is good, since on first render you might actually get undefined. This might also be true for the click handler, cause request to server might get stuck, or fail.
Therefore you need to guard against that kind of value. If it's undefined , you might want to provide some fallback value, or even some error page.
When you are sure that the value would be there (you should not, cause you user might have a crappy network connection from his mobile phone) you might overwrite it with typescript assertion. But i think you should be more defensive and provide a fallback when the value would not be there as you are anticipating.
As for your custom hook, you might want to provide there a…

Replies: 3 comments 1 reply

You must be logged in to vote
0 replies

You must be logged in to vote
1 reply
@ebisbe

Answer selected by Vincent-HD

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
Q&A
Labels
None yet
3 participants