【问题标题】:React typescript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index typeReact typescript - 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型
【发布时间】:2021-02-28 16:49:12
【问题描述】:

我有一个演示 here

我知道这不是一个好问题,但我演示中的工作代码导致我的实际代码出错。

我有一个简单的 React typescript 应用程序,它只显示来自 json 数据的值。

在我的演示中这是可行的,但在我的实际代码中(几乎完全相同)我得到一个打字稿错误。

错误在这里{ProductData[key]

元素隐含地具有“任何”类型,因为类型的表达式 'string' 不能用于索引类型

我想我需要创建一个接口来描述 json 和链接,但我不确定该接口应该是什么样子

<div>
  <ul>
    {Object.keys(ProductData).map(key => (
      <li key={key}>{ProductData[key].ProductSize.min}</li>
    ))}
  </ul>
</div>

【问题讨论】:

  • 请分享您的 ProductData 结构模型

标签: reactjs typescript


【解决方案1】:

可以尝试这种方式,但不建议迭代对象以创建数组,因为Object.keys(或任何对对象的迭代)不能保证项目的顺序。

只为这个用例使用数组。

此外,类型推断并不总是像魔术一样工作。有很多书面文章描述了它如何以及为什么这样工作。 例如)https://stackoverflow.com/a/55012175/5755608 例如)https://github.com/microsoft/TypeScript/pull/12253#issuecomment-263132208

// example 1
import ProductData from "./product.json";

type ProductDetail = {
  ProductSize?: {
    min: number;
    max?: number;
  };
  ProductHeight?: {
    min: number;
    max?: number;
  };
  ProductSpacing?: number;
  ProductWeight: number;
};

const App = () => {
  return (
    <div>
      <ul>
        {Object.entries(ProductData).map(
          ([key, value]: [string, ProductDetail]) => (
            <li key={key}>{value.ProductSize.min}</li>
          )
        )}
      </ul>
    </div>
  );
};

也可以尝试这种方式,但限制很少。

  1. 由于信息的限制,无法像您想象的那样推断 ProductData 的类型
  2. 需要转换键的类型,因为它也可能是类型符号
// example 2
const App = () => {
  return (
    <div>
      <ul>
        {Reflect.ownKeys(ProductData).map((key) => (
          <li key={key as string}>{ProductData[key].ProductSize.min}</li>
        ))}
      </ul>
    </div>
  );
};

【讨论】:

    猜你喜欢
    • 2021-05-04
    • 2020-11-13
    • 2019-12-17
    • 1970-01-01
    • 2021-03-17
    • 2021-04-20
    • 1970-01-01
    • 2020-10-29
    • 2020-10-04
    相关资源
    最近更新 更多