How can I get an element by index in Typescript+React? I keep getting the error: Element implicitly has an ‘any’ type because expression of type ‘0’ can’t be used to index type ‘{ code: string; name: string; dateTime: string; }’. Maybe it’s a stupid, but I don’t have much experience with Typescript, and I would like departure[0] and then departure[1] to be displayed separately on the page
const [result, setResult] = useState<ConversionData[]>([]);
type ConversionData = {
uuid: string;
airlineCode: string;
price: {
amount: number;
currency: string;
};
bounds: Array<{
departure: {
code: string;
name: string;
dateTime: string;
};
destination: {
code: string;
name: string;
dateTime: string;
};
duration: string;
}>;
};
useEffect(() => {
const api = async () => {
const data = await fetch("http://localhost:3001/flights").then((res) =>
res.json()
);
setResult(data);
};
api();
}, []);
return (
<div className="App">
{result.map((value) => {
return (
<>
{" "}
<div className="container">
{value?.bounds.map((newvalue) => {
const departure = newvalue.departure;
const destination = newvalue.destination;
const dates = new Date(departure.dateTime);
const dates2 = new Date(destination.dateTime);
return (
<>
<div>
<img
src={
"https://d1ufw0nild2mi8.cloudfront.net/images/airlines/V2/srp/result_desktop/" +
value.airlineCode +
".png"
}
/>
{departure.code}
<br />
do {destination.code}
<br />
Xxx:
{dates.getUTCHours()}
Xxx:
{dates2.getUTCHours()}
<br />
{dates.getUTCDate()}-
{dates.toLocaleString("en-US", { month: "short" })}-
{dates.getUTCFullYear()}
Xxx
{dates2.getUTCDate()}-
{dates2.toLocaleString("en-US", { month: "short" })}-
{dates2.getUTCFullYear()}
<div className="line" />
</div>
</>
);
})}
I searched on internet and found solutions with keyof but it doesn’t work
2
Answers
I did a double mapp unnecessarily. I needed bounds[0].departure as in comment
It sounds like the
data
object needs to be cast as theConversionData
type. Whenfetch
returned the data, it’s unaware of what type it is.setResult(data as ConversionData[]);
You may first need to cast it to
unknown
:setResult(data as unknown as ConversionData[]);