【问题标题】:Property ' name ' does not exist on type' [ ] '类型“[]”上不存在属性“名称”
【发布时间】:2019-12-10 21:54:25
【问题描述】:

我在属性 products 中声明数组 IProducts 如下所示.. 但令我恼火的是他们没有识别 productName 已声明..请我需要帮助

product-list.component.ts

filteredProducts: IProduct[];
products : IProduct[] = [{
        "productId": 2 ,
        "productName": "Garden Cart" ,
        "productCode": "GDN-0023" ,
        "releaseDate": "March 18,2018",
        "description":  " 15 gallon capacity rolling",
        "price" :   32.99,
        "starRating": 4.2,
        "imageUrl" : "http://openclipart.org/image/300px/sgv_to_png/58471/garden_cart.png",

    },
    {

        "productId": 5 ,
        "productName": "Hammer" ,
        "productCode": "TBX-0048" ,
        "releaseDate": "May 21,2016",
        "description":  " Curved claw steel Hammer",
        "price" :   8.9,
        "starRating": 4.8,
        "imageUrl" : "http://openclipart.org/image",


    }
] ;

constructor() {

  this.filteredProducts = this.products;
  this.listFilter = 'cart';
}

performFilter(filterBy: string): IProduct[]{
    filterBy =filterBy.toLocaleLowerCase();
    return this.products.filter((product: IProduct) =>
        this.products.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
}

终端生成以下错误:“src/app/products/product-list.component.ts(131,27): error TS2339: Property 'productName' does not exist on type 'IProduct[]'.”

【问题讨论】:

  • 看起来不错,我猜您的数组没有名为 productName 的属性,但数组中的单个产品可能有;)

标签: angular typescript


【解决方案1】:

我要从你所展示的内容出发,说this.productsIProduct 的数组。

您正在尝试访问数组的属性productName,您需要指定要访问的数组的哪个元素。幸运的是,您已经可以访问过滤器功能中的元素,因此您可以这样做

return this.products.filter((product: IProduct) =>
            product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);

【讨论】:

    【解决方案2】:

    你的语法有问题 这是解决此问题的方法:

    performFilter(filterBy: string): IProduct[]{
            filterBy =filterBy.toLocaleLowerCase();
            return this.products.filter((product: IProduct) =>
                product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1
        )}
    

    基本上它遍历数组,其中 product: IProduct 是数组的一个元素

    【讨论】:

      【解决方案3】:

      IProduct 必须是模态的,productName 必须是其中的属性。

      或者只使用products: any 而不是products: IProduct[]

      【讨论】:

        猜你喜欢
        • 2020-11-20
        • 1970-01-01
        • 1970-01-01
        • 2017-10-21
        • 1970-01-01
        • 2019-08-18
        • 2019-09-13
        • 2021-10-10
        • 1970-01-01
        相关资源
        最近更新 更多