类型'{}'不能分配给类型'{title:string;文字:字串; }' [英] Type '{}' is not assignable to type '{ title: string; text: string; }'

查看:82
本文介绍了类型'{}'不能分配给类型'{title:string;文字:字串; }'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于下面的TypeScript代码,我遇到了以下错误,

I am getting below error for below TypeScript code,

类型'{}'不能分配给类型'{title:string;文字:字串; }'.类型"{}"中缺少属性标题".

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)!');
        }
    }
}

推荐答案

您告诉编译器article类型为{ title: string, text: string },但是随后您分配了一个空对象({}),该对象同时缺少titletext,所以编译器会抱怨.

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;文字:字串; }'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆