[英]Angular Property 'content' does not exist on type 'never'
所以代码很简单,我有一个组件,我想在其中呈现信息(如果存在),当组件不存在时我得到错误。
所以 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 {}
}
我收到此错误:错误图片
您没有为您的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[] = [];
...
}
因此,typescript 将推断出正确的类型。
您只需要正确输入您的posts
属性:
interface Post {
title:string;
content: string;
}
export class PostListComponent {
posts: Post[] = []; // <-- proper typings
}
在 VS 代码中只是给出错误,因为 typescript 正在验证类型,所以在 angular 代码本身中没有定义类型。
理想情况下,您可以在 PostListComponent class 之外的某处定义帖子类型
export interface Post {
title: string;
content: string;
}
在您的 PostListComponent 中定义这样的类型
posts: Post[] = [];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.