So I have this code
In my application user
could be undefined
(It later get set after api call). I want to set user
type to be UserRecord | undefined
. So that when I tried to get userId
it should throw typescript warning/error that user
could be undefined
.
I tried this, but it doesn’t work as expected.
My needs is that typescript should throw error when I try to access ._id
without checking user
type yet. How I can define type?
2
Answers
You can solve this by using TypeScript optional chaining operator(?).
This is happening because strict null checks are apparently not enabled. When that setting is not on, typescript basically ignores
null
andundefined
. Once you turn it on, both of the lines of code you had screenshots of should work as expected.You can turn on strict mode by adding this line to your
tsconfig
file:If for some reason you just want strictNullChecks, but not the rest of strict mode the following is also possible, though i’d recommend using the full strict mode: