I am learning angular 2, and in this example where I set the variable for isLoading to true, and then change it to false, once I fetch the data I need, I get the error:
Typescript - type 'false' is not assignable to type 'true'
This is the code:
export class AppComponent implements OnInit {
isLoading: true;
constructor(private _articleService: ArticleService, private _postService: PostService){}
ngOnInit(){
this.articles = this._articleService.getArticles();
this._postService.getPosts()
.subscribe(posts => {
this.isLoading = false;
console.log(posts[0].title);
});
}
The "Type 'X' is not assignable to type 'boolean'" TypeScript error occurs when a value that is not a boolean is assigned to something that expects a boolean . To solve the error, convert the value to a boolean or use a type guard to verify value is a boolean before the assignment.
The "Type 'boolean | undefined' is not assignable to type boolean" error occurs when a possibly undefined value is assigned to something that expects a boolean . To solve the error, use the non-null assertion operator or a type guard to verify the value is a boolean before the assignment.
You can assign true , false and undefined and null to boolean in TypeScript without strict null checks.
The "Type 'void' is not assignable to type" TypeScript error occurs when we forget to return a value from a function, so the function gets an implicit return type of void . To solve the error, make sure you return a value of the correct type from your functions before the assignment.
Not required to define the type of variable at a time, but you should set to find bugs during development. In addition editor before know to complete the code thus he knows the type of the variable.
export class AppComponent implements OnInit {
isLoading : boolean = true;
constructor(private _articleService: ArticleService, private _postService: PostService){}
ngOnInit(){
this.articles = this._articleService.getArticles();
this._postService.getPosts()
.subscribe(posts => {
this.isLoading = false;
console.log(posts[0].title);
});
}
isLoading: true;
means that the only value you can assign to isLoading
is the value true
. You want isLoading: boolean
.
Based on suggestions from comments and the answer from @Louis, this was the right syntax to fix it:
isLoading: boolean = true;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With