[英]React typescript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
I know this isn't a good question but the working code in my demo is causing an error in my actual code.我知道这不是一个好问题,但我演示中的工作代码导致我的实际代码出错。
I have a simple React typescript app that just displays value from json data.我有一个简单的 React typescript 应用程序,它只显示来自 json 数据的值。
In my demo this works but in my actual code (that is nearly exactly the same) I get a typescript error.在我的演示中,这有效,但在我的实际代码中(几乎完全相同),我收到了一个打字稿错误。
The error is here {ProductData[key]
错误在这里
{ProductData[key]
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型
I think I need to create an interface to describe the json and link that but I'm not sure how that interface should look我想我需要创建一个接口来描述 json 并链接它,但我不确定该接口应该是什么样子
<div>
<ul>
{Object.keys(ProductData).map(key => (
<li key={key}>{ProductData[key].ProductSize.min}</li>
))}
</ul>
</div>
can try this way, but not recommend to iterate object to create array as Object.keys
(or any iteration over object) does not guarantees order of items.可以尝试这种方式,但不建议迭代对象来创建数组,因为
Object.keys
(或任何对对象的迭代)不能保证项目的顺序。
just use array for this usecase.只需将数组用于此用例。
also, type infer doesnot always work like magic.此外,类型推断并不总是像魔术一样工作。 there are lots of written posts which describes how and why it works that way.
有很多书面文章描述了它如何以及为什么这样工作。 ex) https://stackoverflow.com/a/55012175/5755608 ex) https://github.com/microsoft/TypeScript/pull/12253#issuecomment-263132208
例如) 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>
);
};
also can try this way, but has few limitations.也可以尝试这种方式,但几乎没有限制。
// example 2
const App = () => {
return (
<div>
<ul>
{Reflect.ownKeys(ProductData).map((key) => (
<li key={key as string}>{ProductData[key].ProductSize.min}</li>
))}
</ul>
</div>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.