TypeScript is not type safe
Let’s say we have an API that return true or false ( TILT – Things I learned Today – http://tiltwebapp.azurewebsites.net/ – returns true if I have learned something today )
What is wrong with this code:
public HasTILTToday():Observable<boolean>{
if(!this.wasLoggedIn)return of(false);
return this.http.get<string>(this.baseUrl+’TILT/HasTILTToday’, {
headers: new HttpHeaders(
{
‘Authorization’: ‘CustomBearer ‘ + this.jwt,
‘Content-Type’: ‘application/json’
}),
responseType: ‘text’ as ‘json’})
;
}
…
…
….
Answer : When you subscribe,even the variable is boolean, when you go with typeof is a string ( that contains “true” or “false” ). And this, when you use a *ngIf =”the bool” – it will have undexpected behaviours.
Solution? The rxjs pipe
public HasTILTToday():Observable<boolean>{
if(!this.wasLoggedIn)return of(false);
return this.http.get<string>(this.baseUrl+’TILT/HasTILTToday’, {
headers: new HttpHeaders(
{
‘Authorization’: ‘CustomBearer ‘ + this.jwt,
‘Content-Type’: ‘application/json’
}),
responseType: ‘text’ as ‘json’})
.pipe(
map(it=>it===’true’)
);
}
Leave a Reply