Type '{}' is not assigned to type '{title: string; text: string; } "

I get below errors for code below TypeScript,

Type '{}' is not assigned to type '{title: string; text: string; } ". The 'title' property is not in the type '{}'.

As I declare an β€œarticle” as shown below,

article: { title: string, text: string } = {}; 

What is the reason for this and how to resolve it? Thanks!

 import { Component } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'article-editor', template: ` <p>Title: <input [formControl]="titleControl"></p> <p>Text: <input [formControl]="textControl"></p> <p><button (click)="saveArticle()">Save</button></p> <hr /> <p>Preview:</p> <div style="border:1px solid #999;margin:50px;"> <h1>{{article.title}}</h1> <p>{{article.text}}</p> </div> ` }) export class ArticleEditorComponent { article: { title: string, text: string } = {}; titleControl: FormControl = new FormControl(null, Validators.required); textControl: FormControl = new FormControl(null, Validators.required); articleFormGroup: FormGroup = new FormGroup({ title: this.titleControl, text: this.textControl }); saveArticle() { if (this.articleFormGroup.valid) { this.article = this.articleFormGroup.value; } else { console.log('Missing field(s)!'); } } } 
+6
source share
2 answers

You told the compiler that article is of type { title: string, text: string } , but then you assign an empty object ( {} ) that does not have both title and text , so the compiler complains.

You can use a type statement to tell the compiler that this is normal:

 let article: { title: string, text: string } = {} as { title: string, text: string }; 

You can also put this in an alias like:

 type MyType = { title: string, text: string }; let article: MyType = {} as MyType; 

And since you are using a type statement, you can simply:

 let article = {} as MyType; 
+10
source

The reason is pretty simple because you are claiming that article should have title and text fields, but {} not. How to solve it depends on what you want to show, and article has an initial value, but the simplest solution would be to make the fields optional: { title?: string, text?: string } .

+4
source

Source: https://habr.com/ru/post/1014764/


All Articles