search

Home  >  Q&A  >  body text

Null value type checking

<p>I just wrote a method in a service, but I'm running into an issue where the type hints that I might be returning a null value, even though I've done a null check in the if statement block. </p> <pre class="brush:php;toolbar:false;">public async getUserById(id: string): Promise<UserEntity> { const user = this.userRepository.getById(id); // returns <UserEntity | null> if (!user) { // checking for null throw new NotFoundUser(`Not found user`); } // Type 'UserEntity | null' is not assignable to type 'UserEntity'. // Type 'null' is not assignable to type 'UserEntity'. return user; }</pre> <p>I want to throw an exception if the user variable is empty and return the UserEntity if not. <br /><br />If I put two exclamation points there, the problem is solved. </p><p><br /></p> <pre class="brush:php;toolbar:false;">if (!!user) { // checking for null throw new NotFoundUser(`Not found user`); }</pre> <p>But if I type !!null in the console it will return false, so in this case I never get into a situation where an exception is thrown. Why does this behavior occur? </p>
P粉896751037P粉896751037477 days ago508

reply all(1)I'll reply

  • P粉267791326

    P粉2677913262023-08-04 10:36:33

    Because !! is similar to Boolean, so in this line of code, you do something similar to Boolean(null), so you will get false, because in Boolean value, null is false. You can use user === null to check if it is null.

    reply
    0
  • Cancelreply