TS2339:属性 'text' 在类型“{}”上不存在

TS2339: Property 'text' does not exist on type '{}'

我实际上正面临这一行问题:- <input [(ngModel)]="question.text" name="question" matInput placeholder="Question">这里是 .text 扩展名问题。这里我使用了 Angular11。这是我的代码。

Question.component.html

<mat-card >

<mat-card-content>

<form>
   
    <mat-form-field>
      <mat-label>Question</mat-label>
      <input [(ngModel)]="question.text" name="question" matInput placeholder="Question">
    </mat-form-field>
  
  </form>
</mat-card-content>


<mat-card-actions>
    <button (click)="post(question)" mat-button>POST</button>
</mat-card-actions>


</mat-card>

question.component.ts

import {Component} from '@angular/core'
import {ApiService} from './api.service'

@Component({

   selector:'question',
   templateUrl:'./question.component.html'

})

export class QuestionComponent{

    question = {}

    constructor(private api:ApiService){}

    post(question)
    {
        this.api.postQuestion(question);
    }
}

当我 运行 我的 application.then 我发现这些错误:-

src/app/question.component.ts:7:16
    7    templateUrl:'./question.component.html'
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component QuestionComponent.


Error: src/app/question.component.html:9:36 - error TS2339: Property 'text' does not exist on type '{}'.

9       <input [(ngModel)]="question.text" name="question" matInput placeholder="Question">
                                     ~~~~

  src/app/question.component.ts:7:16
    7    templateUrl:'./question.component.html'
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component QuestionComponent.

如何解决这个问题?

问题

当您创建对象时 question = {} Typescript 将类型推断为 {} 没有属性的对象。如果您尝试访问任何 属性,它会抛出错误

解决方案

设置对象的类型

question: { text?: string; } = {}

或者甚至更好地声明一个接口

interface IQuestion {
  text?: string;
}

...
question: IQuestion = {}

这是因为您的对象“question”中没有任何名称为“text”的键 您可以在对象中添加一个名为“text”的键,也可以为对象“question”提供类型定义。 如下所示:

interface Iobject {
    text: string;
}

question: Iobject;

这样做你的错误就会消失。

您应该将 question 对象的类型更改为任何

question: any = {};

创建接口:

    interface Question {
       text?: string;
       // other properties if you have ones
    }

然后将问题类型设置为Question

question: Question = {}

这是一个有效的 example

这有助于任何:

let a : any = {};

您必须声明以 'question' 命名的 属性 的类型。您可以尝试关注,

question:any = {};

最近更新版本的typescript严格类型检查问题。如果你正在使用 Angular 那么你可以通过这种方式轻松关闭这种严格的类型检查,