[英]Why my property does not exist on type 'never'
I'm trying to type a ts file which is for some slices in react js using redux.我正在尝试使用 redux 键入一个 ts 文件,该文件用于反应 js 中的某些切片。 The problem is that I keep having this error: "Property 'quantity' does not exist on type 'never'.".
问题是我一直有这个错误:“'never'类型上不存在属性'数量'。”。
Here's the code:这是代码:
addToCart: (state, action) => {
const itemInCart = state.cart.find(
(item: Record<string, unknown>) => item.id === action.payload.id
)
if (itemInCart) {
itemInCart.quantity++
} else {
state.cart.push({ ...action.payload, quantity: 1 })
}
},
I tried to add the Record<string, unknown> type but this doesn't make any changes.我尝试添加 Record<string, unknown> 类型,但这并没有做出任何改变。 Do you have any suggestions?
你有什么建议吗?
By typing item
as Record<string, unknown>
you're typing any property of item to be unknown.通过将
item
键入Record<string, unknown>
您将 item 的任何属性键入为未知。 This means item.id and itemInCart.quantity are both unknown types.这意味着 item.id 和 itemInCart.quantity 都是未知类型。 You can not increment an unknown type.
您不能增加未知类型。
Quick fix If you don't mind switching to type-less code, you can change Record<string, unknown>
to Record<string, any>
and it would work.快速修复如果您不介意切换到无类型代码,您可以将
Record<string, unknown>
更改为Record<string, any>
并且它会起作用。 Or if that doesn't work you can try changing const itemInCart
to const itemInCart: any
.或者,如果这不起作用,您可以尝试将
const itemInCart
更改为const itemInCart: any
。
Better fix Create a type or interface for items in your cart.更好地修复为购物车中的物品创建类型或界面。 Eg:
例如:
interface CartItem {
id: string;
quentity: number;
}
(I'm assuming here that id is a string, you can change it to whatever is the actual type) And then use Record<string, CartItem>
(我在这里假设 id 是一个字符串,您可以将其更改为实际类型)然后使用
Record<string, CartItem>
Try writing it like this:试着这样写:
const [arr, setArr] = useState<any[]>([])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.