【问题标题】:Angular Property 'content' does not exist on type 'never'“从不”类型上不存在 Angular 属性“内容”
【发布时间】:2021-05-29 22:22:46
【问题描述】:

所以代码很简单,我有一个组件,我想在其中呈现信息(如果存在),当组件不存在时我得到错误。

所以 post-list.component.html 看起来像这样:

  <mat-expansion-panel *ngFor="let post of posts">
    <mat-expansion-panel-header>
      <mat-panel-title>
        {{ post.title }}
      </mat-panel-title>
      <!-- <mat-panel-description>
        {{post.description}}
      </mat-panel-description> -->
    </mat-expansion-panel-header>
    <p>{{ post.content }}</p>
  </mat-expansion-panel>
</mat-accordion>
<p *ngIf="posts.length >= 0">No posts added yet</p>

post-list.components.ts 看起来像这样>

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-post-list',
  templateUrl: './post-list.component.html',
  styleUrls: ['./post-list.component.css'],
})
export class PostListComponent implements OnInit {
  constructor() {}

  posts = [];

  ngOnInit(): void {}
}

我收到此错误: Error image

【问题讨论】:

    标签: javascript angular mean-stack


    【解决方案1】:

    您没有为 posts 属性定义类型。当你这样做时

    export class PostListComponent implements OnInit {
      ...
      posts = [];
      ...
    }
    

    typescript 从[] 的值推断posts 属性的类型。并且从一个没有任何输入信息的空数组中得出never[],因此它假设如下

    export class PostListComponent implements OnInit {
      ...
      posts: never[] = [];
      ...
    }
    

    要解决此问题,请为您的 posts 属性定义一个类型,例如

    export interface IPost {
      title: string;
      content: string;
      ...
    }
    
    export class PostListComponent implements OnInit {
      ...
      posts: IPost[] = [];
      ...
    }
    

    因此,打字稿将推断出正确的类型。

    【讨论】:

      【解决方案2】:

      您只需正确输入您的 posts 属性:

      interface Post {
        title:string;
        content: string;
      }
      
      
      export class PostListComponent {
        posts: Post[] = []; // <-- proper typings
      }
      
      

      【讨论】:

        【解决方案3】:

        在 VS 代码中只是给出错误,因为打字稿正在验证类型,所以角度代码本身没有定义类型。

        理想情况下,您可以在 PostListComponent 类之外的某个地方定义帖子类型

        export interface Post {
         title: string;
         content: string;
        }
        

        在你的 PostListComponent 中定义这样的类型

        posts: Post[] = [];
        

        【讨论】:

          猜你喜欢
          • 2018-07-12
          • 2018-05-01
          • 2023-03-18
          • 2017-10-24
          • 1970-01-01
          • 2022-07-23
          • 2021-04-02
          • 2021-12-30
          • 2017-04-09
          相关资源
          最近更新 更多