【问题标题】:How to access object property with dynamic key in Typescript?如何在 Typescript 中使用动态键访问对象属性?
【发布时间】: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


【解决方案1】:

我通过声明这样的接口让它工作:

interface Variant {
  [key: string]: string | number | string[];
}

然后

(updatedVariant as Variant)[key] = e.currentTarget.value;

我的错误是认为key 缺少类型或其他东西,而实际上我需要updatedVariant 的接口。

【讨论】:

    猜你喜欢
    • 2020-10-07
    • 2017-08-10
    • 2018-08-13
    • 2021-02-27
    • 2011-06-15
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    相关资源
    最近更新 更多