typescript - “从不”类型上不存在属性。在一个函数中
问题描述
//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 = [];
推荐阅读
- php - phpseclib 无法读取包含 guillemet 括号的 CSR 字段
- docker - 如何在 kubernetes 中添加 pod 依赖项,就像 docker-compose.yml 中的“depends_on”一样
- youtube - YouTube 还在使用 DASH 吗?
- ios - Scenekit:为什么我的相机看不到远处的物体?
- python - 如何从python中提取HTML文件中的特定行?
- r - 无法启动 rstudio(安装在 Anaconda 中)
- python - 在python中将日期时间写入CSV文件?
- reactjs - 添加导入对象时的括号表示法
- php - 从 API 获取 json 数据,如何以表格格式或引导程序在循环中显示数据
- amazon-web-services - 潜望镜式应用架构