How can I resolve TS7015 in my TypeScript/Next.js/React project when using an index expression that is not of type number?
You can't access the item by a property of the object using the square bracket syntax.
Assuming that current_product is the name of the product (might be id, but I can't see the Product type), you need to do the following:
const main_image = data !== null ? data.find(product => product === current_product).main_image : null;


I Got Element implicitly has an 'any' type because index expression is not of type 'number'.ts(7015) error
I have Improted this file
import { useAmazon } from "@context/amazon";
I have Used hear
const { data, current_product } = useAmazon();
and Got error
const main_image = data[current_product].main_image; // error in current_product
@context/amazon file
import { JSObject } from "@classes/JSObject";
import React, { useState, useEffect, useContext, createContext } from "react";
import axios from "axios";
import { Product } from "types";

type AmazonContextType = {
  data: Product[] | null;
  current_product: string;
  setProduct: (product: string) => void;
  offers: JSObject | null;
  setOffers: (offer: JSObject | null) => void;
};

type Props = {
  children: React.ReactNode;
};

const amazonDefault: AmazonContextType = {
  data: null,
  current_product: '',
  setProduct: () => undefined,
  offers: null,
  setOffers: () => undefined,
};

const AmazonContext = createContext<AmazonContextType>(amazonDefault);

export function useAmazon() {
  return useContext(AmazonContext);
}

export function AmazonProvider({ children }: Props) {
  const [data, setData] = useState(amazonDefault.data);
  const [current_product, setProduct] = useState(amazonDefault.current_product);
  const [offers, setOffers] = useState(amazonDefault.offers);

  useEffect(() => {
    const fetchData = async () => {
      const url =
        "https://getdata.com/abc";
      const result = await axios(url);
      setData(result.data.payload);
      
      
    };
    fetchData();
  }, []);

  return (
    
    <AmazonContext.Provider
      value={{ data, current_product, setProduct, offers, setOffers }}
    >
      
      {children}
    </AmazonContext.Provider>
  );
}

How i can Solve this Error
const main_image = typeof current_product === 'string' ? data[current_product as keyof typeof data].main_image : null; 
I have also try chatGPT and google bard
keyword
typescript
next.js
reactjs
javascript
json
