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
1条答案
按热度按时间guz6ccqo1#
不能使用方括号语法通过对象的属性访问该项。假设current_product是产品的
name
(可能是id
,但我看不到Product
类型),您需要执行以下操作: