【问题标题】:Type '{}[]' is not assignable to type 'ShoppingCartItem[]'类型“{}[]”不可分配给类型“ShoppingCartItem[]”
【发布时间】:2018-05-29 03:13:39
【问题描述】:

我试图解决这个问题很长时间了。编译器显示错误,但如果我重新编译,程序仍然可以正常运行。帮助解决错误。 错误:

类型“{}[]”不可分配给类型“ShoppingCartItem[]”。类型 '{}' 不可分配给类型 'ShoppingCartItem'。 类型“{}”中缺少属性“产品”。

我的服务.ts
async getCart():Promise<Observable<ShoppingCarts>>{ let cartId = await localStorage.getItem('cartId') return this.shoppingCartCollection.doc(cartId).collection('items').valueChanges() .map(data => new ShoppingCarts(data)) } 我的班级和界面

    export interface ShoppingCartItem{
    product:Product;
    quantity:number;
}
export class ShoppingCarts{
    constructor(public shoppingItems:Array<ShoppingCartItem>){}
    get getProducts(){
        return this.shoppingItems.filter(element => (element.quantity != 0));
    }
    get totalItemsCount(){
        let count = 0;
        for (let product of this.shoppingItems)
            count += product.quantity
        return count;
    }
}

产品界面

export interface Product {
    title:string,
    price:number,
    $key:string,
    category:string,
    imageUrl:string
};


我得到的对象是:

(5) [{…}, {…}, {…}, {…}, {…}]
0:product:{$key: "02loEh33W51bSkfBXgqN", category: "Bread", imageUrl: "https://upload.wikimedia.org/wikipedia/commons/1/1d/Bagel-Plain-Alt.jpg", price: 2.4, title: "Bagel Bread"}
quantity:2
__proto__:Object
1:product:{$key: "1xrkYBMg4GYh4JKe8wpp", category: "Fruits", imageUrl: "http://www.picserver.org/pictures/apple01-lg.jpg", price: 5, title: "Apple"}
quantity:4
__proto__:Object
2:
product:{$key: "3frhYw5TlyGnnwM9opb5", category: "Fruits", imageUrl: "https://upload.wikimedia.org/wikipedia/commons/c/c4/Orange-Fruit-Pieces.jpg", price: 4.5, title: "Orange"}
quantity:1
__proto__:Object
3:{product: {…}, quantity: 0}
4:{product: {…}, quantity: 1}
length:5

【问题讨论】:

  • 编译器到底在抱怨哪一行/表达式?
  • 你可以试试return this.shoppingCartCollection.doc(cartId).collection&lt;ShoppingCartItem&gt;('items').valueChanges()

标签: angular typescript google-cloud-firestore


【解决方案1】:

由于缺少发生错误的确切行或代码部分,我使用以下代码重现了错误:

interface ShoppingCartItem {
  product: string;
}

class ShoppingCart implements ShoppingCartItem {
  product: string; 
}

const t: ShoppingCartItem[] = [{}]; // TS2322 [..]  Property 'product' is missing in type '{}'

要解决这个问题,只需键入强制转换空对象:

const t: ShoppingCartItem[] = [{} as ShoppingCartItem];

【讨论】:

  • 您好...谢谢您的帮助。错误是在服务的地图功能中产生的,我返回新的 ShoppingCartItem 对象并传递数据。
  • 啊,然后像这样输入构造函数参数:.map(data =&gt; new ShoppingCarts(data as ShoppingCartItem[])),因为此时数据没有具体类型。
猜你喜欢
  • 2020-04-02
  • 2019-06-02
  • 2018-01-04
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 2023-01-28
相关资源
最近更新 更多