简体   繁体   English

在 Angular 中使用过滤器时,类型“类”上不存在属性

[英]Property does not exist on type 'Class' when using filter in Angular

I am using array.filter in an Angular pipe, and I imported a class I have created:我在array.filter中使用 array.filter,并导入了我创建的 class:

import { Pipe, PipeTransform } from '@angular/core';
import Product from '../models/Product';

@Pipe({
  name: 'products'
})
export class ProductsPipe implements PipeTransform {

  transform(products: Product[], valueToSearch: string): any {
    return products.filter( product => product.name);
  }

}

For some reason, I am getting this error: Property 'name' does not exist on type 'Product' , which is funny, because it absolutely does exist on type Product.出于某种原因,我收到此错误: Property 'name' does not exist on type 'Product' ,这很有趣,因为它绝对存在于 Product 类型上。

This is the second time it happens with filter, can anyone help?这是过滤器第二次发生这种情况,有人可以帮忙吗?

The Model: Model:


export default class Product {
    public constructor(
        ID: number,
        name: string,
        category: string,
        price: number,
        imageURL: string
    ) {};
}

I managed to figure it out, my model did not have his properties as 'public'.我设法弄清楚了,我的 model 没有他的“公共”属性。

I managed to figure it out, my model did not have his properties as 'public'.我设法弄清楚了,我的 model 没有他的“公共”属性。 It now looks like this:现在看起来像这样:

export default class Product {
    public constructor(
        public ID: number,
        public name: string,
        public category: string,
        public price: number,
        public imageURL: string
    ) {};
}

It is great you figured out the issue, another solution would be to use an interface instead.很高兴您解决了这个问题,另一种解决方案是使用界面。 This would be appropriate as your class seems not to have any methods hence interface would be appropriate for typing这将是合适的,因为您的 class 似乎没有任何方法,因此接口适合键入

export interface Product {
   ID: number,
   name: string,
   category: string,
   price: number,
   imageURL: string
}

and import it like import { Product } from '..models/Product'并像import { Product } from '..models/Product'一样导入它

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

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