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
Problem was with not placed await for async function. But that type issue definitely drove me away from real problem
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 withuser === null
Maybe try the following:
I’m not sure but I have a feeling that static hints can help type inference.