问题描述
对于下面的TypeScript代码,我遇到了以下错误,
I am getting below error for below TypeScript code,
当我像下面这样声明文章"时,
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)!');
}
}
}
推荐答案
您告诉编译器article
类型为{ title: string, text: string }
,但是随后您分配了一个空对象({}
),该对象同时缺少title
和text
,所以编译器会抱怨.
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;
这篇关于类型'{}'不能分配给类型'{title:string;文字:字串; }'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!