-2

I have a demo here

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.

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]

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

<div>
  <ul>
    {Object.keys(ProductData).map(key => (
      <li key={key}>{ProductData[key].ProductSize.min}</li>
    ))}
  </ul>
</div>
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
lomine
  • 873
  • 5
  • 20
  • 36

1 Answers1

0

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.

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

// 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.

  1. can not infer type of ProductData as you might imagine due to limitation of infos
  2. need to cast type of key because it could also be type symbol
// example 2
const App = () => {
  return (
    <div>
      <ul>
        {Reflect.ownKeys(ProductData).map((key) => (
          <li key={key as string}>{ProductData[key].ProductSize.min}</li>
        ))}
      </ul>
    </div>
  );
};

lee
  • 21
  • 4