javascript 如何在TypeScript/Next.js/React项目中使用非number类型的索引表达式解析TS 7015?

8yparm6h  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(109)

I Got Element隐式具有“any”类型,因为索引表达式不是“number”类型。ts(7015)错误
我已改进此文件import { useAmazon } from "@context/amazon";
我用过hear const { data, current_product } = useAmazon();
并得到错误const main_image = data[current_product].main_image; // error in current_product
@context/amazon文件

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>
  );
}

如何解决这个错误
const main_image = typeof current_product === 'string' ? data[current_product as keyof typeof data].main_image : null;我也试过chatGPT和google bard
关键字typescript next.js reactjs javascript json

guz6ccqo

guz6ccqo1#

不能使用方括号语法通过对象的属性访问该项。假设current_product是产品的name(可能是id,但我看不到Product类型),您需要执行以下操作:

const main_image = data !== null ? data.find(product => product === current_product).main_image : null;

相关问题