繁体   English   中英

“从不”类型上不存在属性。 在 function

[英]Property does not exist on type 'never'. in a function

    //the error is 
    //(Property 'productId' does not exist on type 'never'.) 
    //and 
    //(Property 'qty' //does not exist on type 'never'.)
    
    
import { Component, OnInit } from '@angular/core';
import { MessengerService } from 'src/app/services/messenger.service';
import { Product } from 'src/app/models/product';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {

  cartItems = [];
  cartTotal = 0
  
   
  
  constructor(private msg: MessengerService) { }

  ngOnInit() {
    this.msg.getMsg().subscribe((product:any = Product) => {
      this.addProductToCart(product)
      
    })
  }

addProductToCart(产品:产品){

  let productExists = false
  

  for (let i in this.cartItems) {
    if (this.cartItems[i].productId === product.id) {
      this.cartItems[i].qty++
      productExists = true
      break;
    }
  }

问题出在这个函数中,productId 和 qty 给出了错误 //(属性 'productId' 在类型 'never' 上不存在。) // 和 //(属性 'qty' // 不存在于类型 'never' 上.)

当你在 typescript 中声明一个空数组时,它的默认类型是 never[]。 尝试 decalare 类型:

cartItems: cartItemType = [];

暂无
暂无

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

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