I'm trying to return a [key, value] pair from a custom response data object, but when I try to loop over each key[value], it's gives me this error:
No index signature with a parameter of type 'string' was found on type 'IResponse'
or
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IResponse'
here's my Detail.tsx:
interface IResponse {
birth_year: string;
created: string;
edited: string;
eye_color: string;
films: string[];
gender: string;
hair_color: string;
heigth: string;
homeworld: string;
mass: string;
name: string;
skin_color: string;
species: string[];
startships: string[];
url: string;
vehicles: string[];
}
const Detail = () => {
const [person, setPerson] = useState<IResponse>({} as IResponse);
const { id } = useParams();
useEffect(() => {
api.get(`people/${id}`).then((res) => {
if (res.data) setPerson(res.data as IResponse);
});
}, [id]);
function printValues() {
return Object.keys(person).map((key) => (
<li>
{key}:{person[key]}
</li>
));
}
return <ul>{printValues()}</ul>;
};
My question is: Why this code:
function objectEntries() {
const a = "name";
const entries = person[a];
console.log(entries);
}
objectEntries();
Works fine and in printValues function doesn't?