user584018 user584018 - 1 year ago 57
TypeScript Question

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

I am getting below error for below TypeScript code,


Type '{}' is not assignable to type '{ title: string; text: string; }'. Property 'title' is missing in type '{}'.


As I am declare "article" like below,

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


What is the reason for it and how to resolve this? 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)!');
}
}
}




Answer Source

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

You can use type assertion to tell the compiler that it's ok:

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

You can also put that into a type alias:

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

And as you're using type assertion then you can simply:

let article = {} as MyType;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download