skip to Main Content

So I have this code

enter image description here

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.

enter image description here

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


  1. You can solve this by using TypeScript optional chaining operator(?).

    const [user, setUser] = useState<UserRecord | undefined>();
    const userId = user?._id;
    
    Login or Signup to reply.
  2. This is happening because strict null checks are apparently not enabled. When that setting is not on, typescript basically ignores null and undefined. 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:

    "strict": true,
    

    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:

    "strictNullChecks": true,
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search