skip to Main Content

I just wrote method in service and faced that types saying me that I may return null while I already made checking for null in if block

    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;
    }

I expected for throw exception in case if user variable is null and return UserEntity if is not null;

If I’m typing double exclamation mark there then problem is gone.

if (!!user) { // checking for null
            throw new NotFoundUser(`Not found user`);
}

But if I’ll type !!null in console, then it will return false, so in this case I’ll never get into throwing exception.
Why is such behavior?

3

Answers


  1. Chosen as BEST ANSWER

    Problem was with not placed await for async function. But that type issue definitely drove me away from real problem


  2. because !! similar to Boolean, in this line you do something like Boolean(null) so you get false because null in boolean is false you can check for null with user === null

    Login or Signup to reply.
  3. Maybe try the following:

    public async getUserById(id: string): NonNullable<Promise<NonNullable <UserEntity>>> {}
    

    I’m not sure but I have a feeling that static hints can help type inference.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search