What I am doing is reading a JSON file located in the public
directory of my React project in the CardContainer
component, as can be seen below:
import { useAsync } from "react-async";
type ProjectData = {
title: string,
desc: string,
website: string,
repo: string,
tags: Array<string>
}
type ProjectContainerData = {
projects: Array<ProjectData>
}
async function getData() {
let output: ProjectContainerData | undefined = undefined;
await fetch("/myProjects.json")
.then((response) => response.text())
.then((data) => {
output = JSON.parse(data);
});
return output;
}
function CardContainer() {
const { data, error, isPending } = useAsync(getData);
for (let project of data?["projects"]) {
// error is here
}
return <></>;
}
export default CardContainer;
When I am editing my code, I see the ':' expected.ts(1005)
error. When I try to compile it with npm start
, I see the same thing:
ERROR in src/components/CardContainer.tsx:27:42
TS1005: ':' expected.
25 | function CardContainer() {
26 | const { data, error, isPending } = useAsync(getData);
> 27 | for (let project of data?["projects"]) {
| ^
28 |
29 | }
30 | return <></>;
My TypeScript version is 4.9.5
. Is there any way to easily avoid this error?
2
Answers
Update: The error goes away when I change this:
to this:
and when I change this:
to this:
?[...]
operator does not exist, the right syntax for it is?.[...]
Hence
?.['projects']
, or?.projects
References: