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>