简体   繁体   English

Angular 类型“从不”上不存在属性“内容”

[英]Angular Property 'content' does not exist on type 'never'

So the code is simple, I have a component where I want to render information (if exists) and I get the error when the component does not exist.所以代码很简单,我有一个组件,我想在其中呈现信息(如果存在),当组件不存在时我得到错误。

So the post-list.component.html looks like this:所以 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>

And the post-list.components.ts looks like this> 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 {}
}

I get this error: Error image我收到此错误:错误图片

You don't have defined a type for your posts property.您没有为您的posts属性定义类型。 When you just do当你做

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

typescript deduces the type for the posts property from its value [] . typescript 从posts属性的值[]推导出类型。 And from an empty array without any typing information it decuces never[] , thus it assumes the following并且从没有任何类型信息的空数组中推断出never[] ,因此它假设以下内容

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

To fix this, define a type for your posts property like要解决此问题,请为您的posts属性定义一个类型,例如

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

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

Thus, typescript will deduce the correct type.因此,typescript 将推断出正确的类型。

You just have to properly type your posts property:您只需要正确输入您的posts属性:

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


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

In VS code just giving the error, because typescript is validating the types, there is no type is defined in the angular code itself.在 VS 代码中只是给出错误,因为 typescript 正在验证类型,所以在 angular 代码本身中没有定义类型。

ideally, you can define the post type somewhere out of the PostListComponent class理想情况下,您可以在 PostListComponent class 之外的某处定义帖子类型

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

In your PostListComponent define the type like this在您的 PostListComponent 中定义这样的类型

posts: Post[] = [];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM