Type ‘X| null’ is not assignable to type ‘boolean’ fix for async pipe in Angular

Luka Onikadze
2 min readApr 29, 2023

Async Pipe is a powerful tool to work with observables. It automatically subscribes to the stream, get’s us the data, and unsubscribes when the components are destroyed. There is one irritating point though; it returns T | null which means that we have to check on null before using it. This makes sense because observable might have no data yet so that it will be null.

Nevertheless, there are lots of cases when we are certain that there will be data in observables and don’t need an extra check on null . So, for example. Let’s imagine the following example

@Component({
selector:'app-component',
template:"
<ng-container *ngIf="users$ | async as users">
<app-users [users]="users"> </app-users>
</ng-container>
"
})
export class AppComponent{

users$= of([ {usernamne:'user1'},{username:'user2'} ]); // dummy data
}

@Component({
selector:'app-users',
template:"
<h1> {{users | json}} </h1>
"
})
export class UsersComponent{
@Input()
users!:User[]
}

even though the data exists in the users$ stream, we still need to check it on null , because async pipe returns T | null so we can’t avoid it in any way. Fortunately, there’s another shorter way

Asyncy Pipe

--

--

No responses yet