Reputation: 516
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?
Upvotes: 3
Views: 343
Reputation: 516
I only need to say to TypeScript that the object can access a [key: string]: value: any on the IResponse interface!
like:
interface IResponse {
[key: string]: your-value-type
[...]
}
Upvotes: 0
Reputation: 765
I see 2 different issues here. First you have to call print values return <ul>{printValues()}</ul>
. Second you are not handling when person.data is empty on the first render before the data is fetched.
Update after comment: Alright since you have these the actual way to fix the type error is like this
let key: keyof IResponse['data'];
for (key in person.data) {
The issue is you do not have any string type keys. So you need to say you are using the keys of that object
If you dont like that syntax you can always use the following instead
for (let [key, value] in Object.entries(person.data))
Upvotes: 2