【发布时间】:2021-11-27 16:08:19
【问题描述】:
在我的组件 Product.tsx 中,我通过 API 调用接收到一个对象,该对象可能如下所示:
{
title: "Product 1",
status: "active",
tax: true,
variants: [
{
id: 1,
sku: 'PRD1',
price: 24.00,
price_reduced: 19.95,
size: 'M'
},
{
id: 2,
sku: 'PRD2',
price: 24.00,
price_reduced: 19.95
size: 'L'
},
]
}
然后我将每个variant 呈现为表格中的一行,其中每一列将价格、大小等显示为可编辑的输入字段。每个input 中的onChange 触发updateVariant(variant.id, key, e);,其中key 是variant 的键之一,e 是输入事件。
updateVariant 应该用给定的key 更新variant 的值,如下所示:
const updateVariant = (
id: number,
key: string,
e: React.FormEvent<HTMLInputElement>
) => {
setProduct((prevState) => {
const update = { ...prevState };
const i = update.variants.findIndex((variant) => variant.id === id);
const updatedVariant = update.variants[i];
updatedVariant[key] = e.currentTarget.value; // errors on this line
update.variants[i] = udpatedVariant;
return update;
});
};
updatedVariant[key] = e.currentTarget.value; 给我一个错误:
Element implicitly has 'any' type because expression of type 'string | number' can't be
used to index type '{id: number, sku: string, ...}'. No index signature with a parameter
of type 'string' was found on type '{id: number, sku: string ...}'
我尝试将其更改为:
updatedVariant[key as keyof typeof updatedVariant] = e.currentTarget.value;
这给了我错误type 'any' is not assignable to type 'never'
我对 Typescript 还很陌生,完全不知道如何进行这项工作。
编辑: 我让它暂时使用
updatedVariant[key as keyof typeof updatedVariant] = e.currentTarget.value as never;
但这不可能是正确/干净的解决方案?
【问题讨论】:
-
试试
updatedVariant[key] = e.currentTarget.value as number | string;
标签: javascript typescript object