角属性'内容'不存在于类型'从不。 [英] Angular Property 'content' does not exist on type 'never'

查看:44
本文介绍了角属性'内容'不存在于类型'从不。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

所以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

推荐答案

您尚未为posts属性定义类型。当您只需要

export class PostListComponent implements OnInit {
  ...
  posts = [];
  ...
}
[]的值推导出posts属性的类型。并从没有任何类型信息的空数组中解码never[],因此它假定如下

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

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

export interface IPost {
  title: string;
  content: string;
  ...
}

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

因此,TypeScrip将推导出正确的类型。

这篇关于角属性&#39;内容&#39;不存在于类型&#39;从不。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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